Posted By

cruelfate on 01/07/11


Tagged

python Net ip address


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

magna


ip.py


 / Published in: Python
 

Convert IPV4 dotted quad to long, or long to dotted quad

  1. # simple IP address calcs
  2.  
  3. import sys, socket, struct
  4.  
  5. def dottedQuadToNum(ip):
  6. "convert decimal dotted quad string to long integer"
  7. return struct.unpack('L',socket.inet_aton(ip))[0]
  8.  
  9. def numToDottedQuad(n):
  10. "convert long int to dotted quad string"
  11. return socket.inet_ntoa(struct.pack('L',n))
  12.  
  13. def makeMask(n):
  14. "return a mask of n bits as a long integer"
  15. return (2L<<n-1)-1
  16.  
  17. def ipToNetAndHost(ip, maskbits):
  18. "returns tuple (network, host) dotted-quad addresses given IP and mask size"
  19.  
  20. n = dottedQuadToNum(ip)
  21. m = makeMask(maskbits)
  22.  
  23. host = n & m
  24. net = n - host
  25.  
  26. return numToDottedQuad(net), numToDottedQuad(host)
  27.  
  28. if __name__=='__main__':
  29. for fn in sys.argv[1:]:
  30. try: print numToDottedQuad(long(fn))
  31. except: print dottedQuadToNum(fn)

Report this snippet  

You need to login to post a comment.