IP address to binary conversion

Greg Jorgensen gregj at pobox.com
Thu Jun 14 04:19:57 EDT 2001


"Jeroen Wolff" <jwolff at ision.nl> wrote in message
news:tedfit8li6m4i5gknj0749v5iriau5fo6q at 4ax.com...
> Hi,
>
> Can somebody help me (a newbee) to convert an ip address to is 32 bits
> representation?

Each of the four numbers in the dotted-quad IP address is the decimal
version of a hex pair. It's already a 32-bit number, you just have to do a
little bit of work.

One way is to simply multiply the address out. For example, given the IP
address 192.168.2.1, the 32-bit equivalent is:

192 * 256^3 + 186 * 256^2 + 2 * 256 + 1 = 3232236033 (0xC0A80201)

Here's one Python solution. Note the long integers: Python's regular signed
integers aren't big enough.

>>> ip = "192.168.2.1"
>>> q = ip.split(".")
>>> n = reduce(lambda a,b: long(a)*256 + long(b), q)
>>> n
3232236033L

The reduce() is equivalent to:

>>> n = long(q[0]) * 256**3 + long(q[1]) * 256**2 + long(q[2]) * 256 +
long(q[3])

You can get a mask m bits long like this:

>>> mask = (long(2)**m) - 1

Now you can simply AND these together to get the network and host portions
of the address:

>>> host = n & mask
>>> net = n - host

Use the %x (or %X) format conversion to see the result in hex:

>>> print "net: %X  host: %X" % (net, host)
net: C0000000  host: A80201


Here's a trickier way to convert a decimal dotted-quad IP address to a hex
string and then to a decimal integer:

>>> # change each decimal portion of IP address to hex pair
>>> hexn = ''.join(["%02X" % long(i) for i in ip.split('.')])
>>> long(hexn, 16)
3232236033L


Enjoy.

Greg Jorgensen
PDXperts LLC
Portland, Oregon USA
gregj at pdxperts.com






More information about the Python-list mailing list