How can I check if an ip is in a network in Python?
Using ipaddress (in the stdlib since 3.3, at PyPi for 2.6/2.7):
>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.1') in ipaddress.ip_network('192.168.0.0/24')
True
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
I like to use netaddr for that:
from netaddr import CIDR, IP
if IP("192.168.0.1") in CIDR("192.168.0.0/24"):
print "Yay!"
As arno_v pointed out in the comments, new version of netaddr does it like this:
from netaddr import IPNetwork, IPAddress
if IPAddress("192.168.0.1") in IPNetwork("192.168.0.0/24"):
print "Yay!"