I’ve been spoiled by PHP! It sometimes makes your job too easy with its large collection of library functions. Python, on the other hand, has a lot of powerful tools for doing low-level stuff. To get something done, which would take a single function call in PHP, you may have to meld together a number of those tools and build a new one.
I was looking for a Python equivalent of PHP’s ip2long() function. which converts an IPv4 address from dotted decimal notation(for example 18.104.22.168) to a 32 bit integer(3494191847). After spending few minutes with Google, I realized that Python has no such function in it’s core or standard library. To achieve this, I had to make use of Python’s socket interface and struct library. Here’s what I did:
from socket import inet_aton
from sturct import unpack
...ip_packed = inet_aton(ip_addr)
...ip = unpack("!L", ip_packed)
Note: Dots(.) in the above code represents indentation. WordPress is eating up the whitespace mysteriously!
The first line inside the ip2long() method, the inet_aton() function, converts the dotted-quad IP address to a 32-bit packed binary format, which is string of four characters in length. To make it an integer, you have to unpack it with the unpack() method, which takes the format as the first argument(which is “!L” in this case, for big-endian unsigned integer) and the packed string as the second. It returns a tuple with the 32-bit integer as the first element.