21st February, 2014


I work with routing data and I need to convert IP addresses between Expanded and Integer notations very frequently. There are a couple of existing options to deal with this:

  1. A few websites like this provide this facility, but frequently switching between a browser and a unix terminal is really a hassle.
  2. A set on *nix tools by the same name, but like other *nix tools this is not available for all unix flavors.


Neither of the above tools was great for me, so one fine day I fired up vi and started coding it myself. As it turned out, this wasn’t a difficult task after all.

Convert an IPv4 address to Integer. Just one line of code:

struct.unpack("!i", socket.inet_pton(socket.AF_INET, addr))[0]
  1. socket.inet_pton(socket.AF_INET, addr) converts an ip address string to a packed binary format.
  2. struct.unpack decodes this binary data. The first argument !i tells that the byte order is network and the data needs to be interpreted to int

Convert an Integer to IPv4 string

socket.inet_ntoa(struct.pack("!i", integer))

This is the exact reverse of the above code. struct.pack encodes the integer to binary data and then socket.inet_ntoa converts the binary data to IPv4 string notation.

A couple of similar lines were added for IPv6 handing, and VoilĂ ..We have a cross platform tool to convert ip address notations.

The source code of this tool is located here. Take a look and feel free to suggest any enhancements or gotchas.

Fork me on GitHub