Getting a netmask in Python

How can I get the network mask of a network device (preferably on Linux, but if it's cross-platform, then it's cool)? I know how in C on Linux, but I can't find a way in Python - maybe minus ctypes. This is or ifconfig parsing. Any other way?

ioctl(socknr, SIOCGIFNETMASK, &ifreq) // C version 
+7
source share
7 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]) 
+8
source

Have you looked here?

http://docs.python.org/library/fcntl.html

This works for me in python 2.5.2 on Linux. Finished it when Ben ran ahead, but still here it goes (it’s sad to waste strength :-)):

 vinko@parrot :~$ more get_netmask.py # get_netmask.py by Vinko Vrsalovic 2009 # Inspired by http://code.activestate.com/recipes/439093/ # and http://code.activestate.com/recipes/439094/ # Code: 0x891b SIOCGIFNETMASK import socket import fcntl import struct import sys def get_netmask(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x891b, struct.pack('256 s',ifname))[20:24]) if len(sys.argv) == 2: print get_netmask(sys.argv[1]) vinko@parrot :~$ python get_netmask.py lo 255.0.0.0 vinko@parrot :~$ python get_netmask.py eth0 255.255.255.0 
+4
source

You can use this library: http://github.com/rlisagor/pynetlinux . Note. I am the author of the library.

+2
source

I had the idea of ​​relying on a subprocess to use a simple ifconfig (Linux) or ipconfig (windows) request to retrieve information (if ip is known). Comments are welcome :

WINDOWS

 ip = '192.168.1.10' #Example proc = subprocess.Popen('ipconfig',stdout=subprocess.PIPE) while True: line = proc.stdout.readline() if ip.encode() in line: break mask = proc.stdout.readline().rstrip().split(b':')[-1].replace(b' ',b'').decode() 

UNIX-Like

 ip = '192.168.1.10' #Example proc = subprocess.Popen('ifconfig',stdout=subprocess.PIPE) while True: line = proc.stdout.readline() if ip.encode() in line: break mask = line.rstrip().split(b':')[-1].replace(b' ',b'').decode() 

IP is retrieved using the socket connection to the network and with getsockname()[0]

+2
source

The netifaces module netifaces worth mentioning here. Directly 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 possibly other UNIX.

+2
source

On Windows, this piece of code can be useful:

 import os import sys import _winreg def main(): adapter_list_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards') adapter_count = _winreg.QueryInfoKey(adapter_list_key)[0] for i in xrange(adapter_count): sub_key_name = _winreg.EnumKey(adapter_list_key, i) adapter_key = _winreg.OpenKey(adapter_list_key, sub_key_name) (adapter_service_name, _) = _winreg.QueryValueEx(adapter_key, "ServiceName") (description, _) = _winreg.QueryValueEx(adapter_key, "Description") adapter_registry_path = os.path.join(r'SYSTEM\ControlSet001\Services', adapter_service_name, "Parameters", "Tcpip") adapter_service_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, adapter_registry_path) (subnet_mask, _) = _winreg.QueryValueEx(adapter_service_key, "SubnetMask") (ip_address, _) = _winreg.QueryValueEx(adapter_service_key, "IpAddress") sys.stdout.write("Name: %s\n" % adapter_service_name) sys.stdout.write("Description: %s\n" % description) sys.stdout.write("SubnetMask: %s\n" % subnet_mask) sys.stdout.write("IpAdress: %s\n" % ip_address) if __name__ == "__main__": main() 

Obtain a list of network adapters from the registry key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards , and then extract additional information about each adapter from the key HKLM\SYSTEM\ControlSet001\Services\{adapter_guid}\Parameters\Tcpip .

I am testing it on Windows XP with 2 virtual adapters, everything works fine. Should work in 2000, 2003 and Vista too.

+1
source

Using the python pyroute2 library, you can get all the attributes of network elements:

 from pyroute2 import IPRoute ip = IPRoute() info = [{'iface': x['index'], 'addr': x.get_attr('IFA_ADDRESS'), 'mask': x['prefixlen']} for x in ip.get_addr()] 

Additional information is available here: http://pyroute2.org/pyroute2-0.3.14p4/iproute.html

0
source

Source: https://habr.com/ru/post/920324/


All Articles