Python - ip <-> subnet match?

0xmtn picture 0xmtn · Mar 15, 2012 · Viewed 14.8k times · Source

Possible Duplicate:
How can I check if an ip is in a network in python

What is the easy way to match subnet to an ip address in python, so that if the ip address is in the subnet I can choose it?

Thanks in advance.

Answer

phihag picture phihag · Mar 15, 2012

In Python 3.3+, you can use ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('192.0.43.10') in ipaddress.ip_network('192.0.0.0/16')
True

If your Python installation is older than 3.3, you can use this backport.


If you want to evaluate a lot of IP addresses this way, you'll probably want to calculate the netmask upfront, like

n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)

Then, for each address, calculate the binary representation with one of

a = int(ipaddress.ip_address('192.0.43.10'))
a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0]  # IPv4 only

Finally, you can simply check:

in_network = (a & mask) == netw