This is probably everywhere, maybe python also comes with it, but I wanted to have my own implementation, and I’ll leave it here for future reference.
Basically, sometimes you don’t want to store IPs in Strings cause they take too much space, instead you want to be a good programmer and store them as 4 bytes (IPv4 that is).
So here’s a couple of functions in python to illustrate the conversion process between string to 4 byte integer, or viceversa:
def ip2num(ipString): if ipString is None: raise Exception("Invalid IP") try: octets = [octet.strip() for octet in ipString.split('.')] except Exception,e: raise e num = (int(octets)<<24) + (int(octets)<<16) + (int(octets)<<8) + int(octets) return num def num2ip(numericIp): if numericIp is None or type(numericIp) != int: raise Exception("Invalid numeric IP. Must be an integer") return str(numericIp >> 24) + '.' + str((numericIp >> 16) & 255) + '.' + str((numericIp >> 8) & 255) + '.' + str(numericIp & 255)