in Code, Geeklife, Python

[Python] ip2num / num2ip – Store an IP string as a 4 byte int.

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")

       octets = [octet.strip() for octet in ipString.split('.')]
    except Exception,e:
        raise e

    num = (int(octets[0])<<24) + (int(octets[1])<<16) + (int(octets[2])<<8) + int(octets[3])
    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)

Write a Comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.