Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get network address and network mask in Python

In my Python script I need to retrieve both the IP address of the machine the script is running on and its network address and its network bytes.

As for the IP address, I found the 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 should I go about finding network address and network bytes? I need to put this information into a filter for tcpdump in the format $NetworkAddress/$NetworkBytes, if that helps at all.

Example:

128.1.2.0/20

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

like image 976
Ricky Robinson Avatar asked Jul 12 '12 13:07

Ricky Robinson


1 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: Retrieving network mask in Python)

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

Update:

If you need cidr (like '128.1.2.0/20'), you can use any of the related libs: 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
like image 144
Antony Hatchkins Avatar answered Oct 12 '22 11:10

Antony Hatchkins