Convert dotted-quad IP addresses to long integer and back, get network and host portions from an IP address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | # IP address manipulation functions
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
hexn = ''.join(["%02X" % long(i) for i in ip.split('.')])
return long(hexn, 16)
def numToDottedQuad(n):
"convert long int to dotted quad string"
d = 256 * 256 * 256
q = []
while d > 0:
m,n = divmod(n,d)
q.append(str(m))
d = d/256
return '.'.join(q)
def makeMask(n):
"return a mask of n bits as a long integer"
return (long(2)**n)-1
def ipToNetAndHost(ip, maskbits):
"returns tuple (network, host) dotted-quad addresses given IP and mask size"
n = dottedQuadToNum(ip)
m = makeMask(maskbits)
host = n & m
net = n - host
return (numToDottedQuad(net), numToDottedQuad(host))
|
An IP address in dotted-quad notation must be converted to an integer to perform bitwise AND and OR operations. In some applications using the decimal integer form may be more convenient or efficient (e.g. storing an IP address in a database).
Tags: network
good base idea, but I think it needs enhancements. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66517 for a version of this useful code that uses Python built-in socket and struct modules to avoid "recoding the wheel".
recoding the wheel. Alex is right--the Python libraries already have functions to do this.
I wrote these functions as part of explaining IP addresses, dotted-quad notation, and masking to someone. I posted them here more as a learning tool than production code.