Packing and unpacking IP addresses into 32-bit integers
Ben Gertzfield
che at debian.org
Mon Aug 9 17:42:44 EDT 1999
Thanks. Here's what I came up with finally. I decided to avoid use
of apply() for clarity, as these are dense enough as it is. :)
import string, struct
def inet_aton(packme):
"""Given a IP address as a string of the form 123.45.67.89, pack
it into the 32-bit binary representation (struct in_addr) used
in C and other languages."""
a, b, c, d = map(string.atoi, string.split(packme, '.'))
return struct.pack('BBBB', a, b, c, d)
def inet_ntoa(packed):
"""Unpacks a 32-bit binary representation of an IP address into a
string and return it in dotted-quad (123.45.67.89) format."""
quads = map(str, struct.unpack('BBBB', packed))
return string.join(quads, '.')
I'm not sure if it's overly-compact, or if I ought to do things with
binary arithmetic for clarity. Anyway, it seems to work. Thanks for
the tip!
Ben
--
Brought to you by the letters O and Q and the number 5.
"I choose YOU! Pikachu!"
Debian GNU/Linux maintainer of Gimp and GTK+ -- http://www.debian.org/
More information about the Python-list
mailing list