Ip format

Tim Chase python.list at tim.thechases.com
Thu Nov 20 12:36:02 CET 2008


> Hello i have this ip 1578568204
> 
> how socket function i can have the ip dotted-quad string?
> 
> i have try socket.inet_aton get no error but only this ^ETB FF


I've got the following program I threw together for one of my 
junior developers:

   from sys import argv, exit
   if len(argv) <> 2:
     print "Usage:"
     print "\t%s <ip_address>" % argv[0]
     print "\t%s <int>" % argv[0]
     print "\nThe first form translates a dotted-quad format into 
int format"
     print "\nThe second form translates from int form to a 
dotted-quad"
     exit(1)

   src = argv[1]

   if src.count('.') == 3:
     a,b,c,d = map(lambda s: 0xff and int(s), src.split('.'))
     print (
       (a << (8*3)) |
       (b << (8*2)) |
       (c << (8*1)) |
       d)
   else:
     i = int(src)
     a = 0xff & (i >> (8*3))
     b = 0xff & (i >> (8*2))
     c = 0xff & (i >> (8*1))
     d = 0xff & (i)
     print '%s.%s.%s.%s' % (a,b,c,d)

The code you're looking for is in the bottom "else:" clause. 
Yes, that could be optimized to just "c = 0xff & (i >> 8)" in the 
3rd case, but it made it easier for my junior developer to 
understand what was going on.

There might be some library function to do these transformations 
for you, but after a quick look, I didn't find anything.

-tkc







More information about the Python-list mailing list