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

You need to login to post a comment.