Packing and unpacking IP addresses into 32-bit integers

Ben Gertzfield che at
Mon Aug 9 16:00:39 EDT 1999

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?


Brought to you by the letters C and X and the number 3.
"A beldam is an old lady."
Debian GNU/Linux maintainer of Gimp and GTK+ --

More information about the Python-list mailing list