How can I check if an ip is in a network in Python?

Staale picture Staale · May 4, 2009 · Viewed 138.5k times · Source

Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?

Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.

Answer

nosklo picture nosklo · May 4, 2009

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!"