Handy IP utilities in python

28 Aug 2010

There are some frameworks for python to handle IP addresses. Sadly they are all very complicated. The following converts an "IPv4 Address" back and forth between a plain old integer and a string in dots-notation (127.0.0.1). From this you can do just about anything.



PUBLIC DOMAIN, but credit always welcome. thanks!



def ip2int(s):
""" Converts a known-good ip address in dots notation into an 32-bit int

"""
parts = [ int(i) for i in s.split('.') ]
return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]

def int2ip(s):
""" Converts an int into dots notation """
return '.'.join((
str((s >> 24) & 0xFF),
str((s >> 16) & 0xFF),
str((s >> 8) & 0xFF),
str( s & 0xFF)
))

def is_internal_ip(s):
""" returns true if ip is 0.0.0.0 or between the intervals

10.0.0.0 / 10.255.255.255
127.0.0.0 / 127.255.255.255

172.16.0.0 / 172.31.255.255

192.168.0.0 / 192.168.255.255

"""
ipi = ip2int(s)
return ipi == 0 or \
(167772160 <= ipi <= 184549375) or \
(2130706432 <= ipi <= 2147483647) or \
(2886729728 <= ipi <= 2887778303) or \
(3232235520 <= ipi <= 3232301055)