21st February, 2014
int2dotted - Convert IP to Integer | Why I love python
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:
- A few websites like this provide this facility, but frequently switching between a browser and a unix terminal is really a hassle.
- 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))
socket.inet_pton(socket.AF_INET, addr)converts an ip address string to a packed binary format.
struct.unpackdecodes this binary data. The first argument
!itells that the byte order is network and the data needs to be interpreted to
Convert an Integer to IPv4 string
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.