1

Dears I was planning to extract my Subnet mask, I had used the below code but the subnetmask is always 255.255.255.255 which is wrong

import socket               # Import socket module
import netifaces

def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    My_ip=s.getsockname()[0]
    s.close()
    return My_ip

def main():
    #print(netifaces.interfaces())

    for i in netifaces.interfaces():
        try:
            # Address
            print("IP Address: ", netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr'])
            print("Mask: ", netifaces.ifaddresses(i)[netifaces.AF_INET][0]['netmask'])
            print("Gateway: ", netifaces.gateways()['default'][netifaces.AF_INET][0])

        except:pass

# This is the IP address of the GateWay

if __name__ == '__main__': main()

The output of the code is:

IPAddress:  192.168.1.4
Mask:  255.255.255.255
Gateway:  192.168.1.1
IP Address:  192.168.231.1
Mask:  255.255.255.255
Gateway:  192.168.1.1
IP Address:  192.168.116.1
Mask:  255.255.255.255
Gateway:  192.168.1.1
IP Address:  10.255.90.137
Mask:  255.255.255.255
Gateway:  192.168.1.1
IP Address:  127.0.0.1
Mask:  255.255.255.255
Gateway:  192.168.1.1

The output of the IPconfig/all on the CMD:

ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . 
   Primary Dns Suffix  . . . . . . .
   Node Type . . . . . . . . . . . . : Peer-Peer
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : 

                                       Home

Wireless LAN adapter Wireless Network Connection 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft Virtual WiFi Miniport Adapter
   Physical Address. . . . . . . . 
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes

Wireless LAN adapter Wireless Network Connection:

   Connection-specific DNS Suffix  . : Home
   Description . . . . . . . . . . . : Broadcom 802.11n Network Adapter
   Physical Address. . . . . . . . . : E4-D5-3D
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::9075:a791:%18(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.1.4(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Lease Obtained. . . . . . . . . . : Thursday, January 12, 2017 4:24:27 PM
   Lease Expires . . . . . . . . . . : Friday, January 13, 2017 5:32:47 PM
   Default Gateway . . . . . . . . . : 192.168.1.1
   DHCP Server . . . . . . . . . . . : 192.168.1.1
   DHCPv6 IAID . . . . . . . . . . . : 585422141
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1C-7C-BD-0D-28-D2-

   DNS Servers . . . . . . . . . . . : 192.168.1.1
                                       192.168.1.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Local Area Connection:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : Home
   Description . . . . . . . . . . . : Realtek PCIe GBE Family Controller #2
   Physical Address. . . . . . . . . : F0-DE
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes

Ethernet adapter VMware Network Adapter VMnet1:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet
1
   Physical Address. . . . . . . . . : 00-50-56-C0-00-01
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::bd6e:92d5%29(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.231.1(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 486559830
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1C-7C-BD-0D-28-D2

   DNS Servers . . . . . . . . . . . : fec0:0:0:f::1%1
                                       fec0:0:0:ffff::2%1
                                       fec0:0:0:ffff::3%1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter VMware Network Adapter VMnet8:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet
8
   Physical Address. . . . . . . . . : 00-50-56-C0-00-08
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::ecf8:fe3f:61b7%30(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.116.1(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 5033046
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1CD-0D-28-D2-44-A0-5E-2F

   DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
                                       fec0:0:0:ffff::2%1
                                       fec0:0:0:ffff::3%1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Local Area Connection* 13:

   Connection-specific DNS Suffix  . : te-data.core
   Description . . . . . . . . . . . : Juniper Networks Virtual Adapter
   Physical Address. . . . . . . . . : 02-05-85-7F-EB-80
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::60c5:1d5a::3ac%32(Preferred)
   IPv4 Address. . . . . . . . . . . : 10.255.90.137(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 989988229
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-1C-7C-BD-0D-28-D2-44-A0-5E-2F

   DNS Servers . . . . . . . . . . . : 10.11.244.6
                                       10.11.240.21
   Primary WINS Server . . . . . . . : 10.11.244.5
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter isatap.{8F32F9B4-16AA-497F-BA87-0CA6C100DAD2}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.te-data.core:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : te-data.core
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{72AB26AD-F4AC-4C29-BE57-D5E87178132D}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #3
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.Home:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : Home
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #4
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{C6CA3E0D-C7E1-4B41-BDAB-74703EB3BC2C}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #5
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
0

2 Answers 2

1

There are alternatives to netifaces on Windows. You can retrieve the interface information using wmic. wmic has a machine readable output option using XML:

wmic nic get /format:rawxml 

A python example to parse this output is available.

Sign up to request clarification or add additional context in comments.

2 Comments

Original question does not suggest or indicate solution only needs to work on Windows. A more OS independent method is provided below but requires a library that is not built-in. There are no small solutions otherwise to the best of my knowledge.
@ScottP it is best to put the detail implied by this comment into your answer directly. IE: specify exactly why the answer to an 8 year old question is "better" or relevant. Also references like "above" or "below" indicate a specific answer ordering that is not universally true.
0
import socket
from ipaddress import IPv4Interface

import netifaces  # not built-in; `pip install netifaces2`


def get_default_interface(target: tuple[str, int] | None = None) -> IPv4Interface:
    """Return the network interface used to connect to target."""
    if target is None:
        target = ("8.8.8.8", 80)  # Google DNS server address
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(target)
            ip_address = s.getsockname()[0]
    except Exception as e:
        logger.warning(f"Failed to auto-detect IP address: {e}")
        ip_address = "127.0.0.1"  # fallback to localhost
    try:
        for dev in netifaces.interfaces():
            for items in netifaces.ifaddresses(dev).values():
                for item in items:
                    if item["addr"] == ip_address:
                        return IPv4Interface(f"{ip_address}/{item['mask']}")
    except Exception as e:
        logger.warning(f"Failed to auto-detect network interface: {e}")
    return IPv4Interface("127.0.0.1/24")  # fallback to localhost

Now to get subnet mask from the interface:

x = get_default_interface()
print(x..with_netmask)
>>> 192.168.1.44/255.255.255.0
subnet_mask = x.with_netmask.split('/')[1]
print(subnet_mask)
>>> 255.255.255.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.