Posted By

rdicicco on 05/07/09

Who likes this?

1 person have marked this snippet as a favorite

Convert IP to Int and Int to IP

/ Published in: Python

Convert an IP address to an integer for easier storage. Also, convert an integer back to an IP address.

`def IntToDottedIP( intip ):        octet = ''        for exp in [3,2,1,0]:                octet = octet + str(intip / ( 256 ** exp )) + "."                intip = intip % ( 256 ** exp )        return(octet.rstrip('.')) def DottedIPToInt( dotted_ip ):        exp = 3        intip = 0        for quad in dotted_ip.split('.'):                intip = intip + (int(quad) * (256 ** exp))                exp = exp - 1        return(intip)`

Comments

Subscribe to comments
Posted By: lukyoung on October 25, 2010

st="127.0.0.1".split('.') int("%02x%02x%02x%02x" % (int(st[0]),int(st[1]),int(st[2]),int(st[3])),16) 2130706433

Posted By: lukyoung on October 25, 2010

``` def test(): pass ```

Posted By: lukyoung on October 25, 2010

Convert dotted quad notation to integer

``` st="127.0.0.1".split('.') int("%02x%02x%02x%02x" % (int(st[0]),int(st[1]),int(st[2]),int(st[3])),16) # = 2130706433 ```

Posted By: rdicicco on June 12, 2015

yes, those are all much easier to read and remember.

Posted By: quetecuestano on September 10, 2015

Some small changes, and now works with Python 3+

``````def IntToDottedIP( intip ):
octet = []
for exp in [3,2,1,0]:
k = 256 ** exp
octet.append(str(intip // k))
intip %=  k
return '.'.join(octet)

def DottedIPToInt( dotted_ip ):
exp = 3
intip = 0
for quad in dotted_ip.split('.'):
intip += int(quad) * (256 ** exp)
exp -= 1
return intip

if __name__=='__main__':
orig_ip = '192.168.2.10'
iip = DottedIPToInt(orig_ip)
fin_ip = IntToDottedIP(iip)
print("Original: {}\nInteger: {}\n..and back again: {}".format(orig_ip, iip, fin_ip))
``````
Posted By: quetecuestano on September 10, 2015

Oops.. I uploaded an older version, here's a (slightly more) efficient implementation:

``````def IntToDottedIP( intip ):
octet = []
for exp in [3,2,1,0]:
q, intip = divmod(intip, 256 ** exp)
octet.append(str(q))
return '.'.join(octet)

def DottedIPToInt( dotted_ip ):
exp = 3
intip = 0
for quad in dotted_ip.split('.'):
intip += int(quad) * (256 ** exp)
exp -= 1
return intip

if __name__=='__main__':
orig_ip = '192.168.2.10'
iip = DottedIPToInt(orig_ip)
fin_ip = IntToDottedIP(iip)
print("Original: {}\nInteger: {}\n..and back again: {}".format(orig_ip, iip, fin_ip))
``````

You need to login to post a comment.