Posted By

rdicicco on 05/07/09


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

blackthorne


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.

  1. def IntToDottedIP( intip ):
  2. octet = ''
  3. for exp in [3,2,1,0]:
  4. octet = octet + str(intip / ( 256 ** exp )) + "."
  5. intip = intip % ( 256 ** exp )
  6. return(octet.rstrip('.'))
  7.  
  8. def DottedIPToInt( dotted_ip ):
  9. exp = 3
  10. intip = 0
  11. for quad in dotted_ip.split('.'):
  12. intip = intip + (int(quad) * (256 ** exp))
  13. exp = exp - 1
  14. return(intip)

Report this snippet  

Comments

RSS Icon 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.