Get network address and netmask in Python

In my Python script, I need to get both the IP address of the computer on which the script is running, and its network address and its network bytes.

Regarding the IP address, I found a solution in the archive:

import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("www.google.com",80)) myAddress = (s.getsockname()[0]) s.close() 

But how do I find the network address and network bytes? I need to put this information in a filter for tcpdump in the format $NetworkAddress/$NetworkBytes , if that helps at all.

Example:

 128.1.2.0/20 

I can find it under inet when I run ip addr . Any easy way to get this info in Python?

+6
source share
2 answers

For Linux, try

 iface = "eth0" socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24]) 

or http://github.com/rlisagor/pynetlinux

(as suggested here: Extracting a netmask in Python )

For Linux, Windows, and MacOS, consider http://alastairs-place.net/projects/netifaces/

Update:

If you need cidr (for example, "128.1.2.0/20"), you can use any of the linked libraries: http://pypi.python.org/pypi?%3Aaction=search&term=cidr&submit=search

For example netaddr :

 >> from netaddr import IPNetwork >> print str(IPNetwork('1.2.3.4/255.255.255.0').cidr) 1.2.3.0/24 
+9
source

You can get any ip related information using pyroute2 :

 from pyroute2 import IPDB ip = IPDB() print(ip.interfaces['em1'].ipaddr) ip.release() 

Or as an option:

 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()] ip.close() 
+1
source

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


All Articles