Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving network mask in Python

Tags:

python

How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?

ioctl(socknr, SIOCGIFNETMASK, &ifreq) // C version
like image 463
Scott Avatar asked Jun 01 '09 19:06

Scott


People also ask

How do I find my net mask?

Use the ifconfig command to confirm that the IP address and netmask are correct. Invoke ifconfig with the name of the network interface that you want to examine. If the interface does not come up, replace the interface cable and try again. If it still fails, use the diag command to check the device.

How do I find my network mask in Linux?

In order to find the subnet mask for your host, use the “ifconfig” command with the interface name and pipe it with the “grep” command to isolate the “mask” string. In this case, you are presented with subnet masks for every network interface (loopback interface included).


2 Answers

This works for me in Python 2.2 on Linux:

iface = "eth0"
socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24])
like image 78
Ben Blank Avatar answered Oct 13 '22 02:10

Ben Blank


The netifaces module deserves a mention here. Straight from the docs:

>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']

>>> addrs = netifaces.ifaddresses('en0')
>>> addrs[netifaces.AF_INET]
[{'broadcast': '10.15.255.255', 'netmask': '255.240.0.0', 'addr': '10.0.1.4'}, {'broadcast': '192.168.0.255', 'addr': '192.168.0.47'}]

Works on Windows, Linux, OS X, and probably other UNIXes.

like image 26
Steven Winfield Avatar answered Oct 13 '22 02:10

Steven Winfield