Packing and unpacking IP addresses into 32-bit integers

Steven D. Majewski sdm7g at Virginia.EDU
Mon Aug 9 22:50:29 CEST 1999


On 9 Aug 1999, Ben Gertzfield wrote:

> I noticed that the 'socket' module in Python has slightly different
> behavior for gethostbyname() than I'm used to.
> 
> In Python, gethostbyname() returns a string, not a packed IP address
> (a 32-bit integer) of the IP address, as C and Perl do.  However, I
> need to talk with C over the network, and the 'struct' module doesn't
> deal with packing or unpacking IP addresses.
> 
> Do I have to use a regular expression to split up the dotted quads
> that gethostbyname() returns into the component bytes and then use
> binary shifts and or'ing to get them into a standard 32-bit integer
> format?  Or is there a better way that I'm totally missing?
> 

No you don't have to use regular expressions and binary shifts and or's:

 First, map int or string.atoi onto the result of applying string.split
 to the return string of gethostbyname -- that will give you a list of ints.

   adr = map( string.atoi, string.split( gethostbyname( name ), '.' ))

and use either struct.pack or array to coerce it into a binary string:

  a = apply( struct.pack, [ 'bbbb' ] + adr )

(or longer, but less cryptically)

  a = array( 'b') 
  a.fromlist( adr )
  a.tostring() 
  a 



---|  Steven D. Majewski   (804-982-0831)  <sdm7g at Virginia.EDU>  |---
---|  Department of Molecular Physiology and Biological Physics  |---
---|  University of Virginia             Health Sciences Center  |---
---|  P.O. Box 10011            Charlottesville, VA  22906-0011  |---





More information about the Python-list mailing list