Welcome, guest | Sign In | My Account | Store | Cart

Convert dotted-quad IP addresses to long integer and back, get network and host portions from an IP address.

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# IP address manipulation functions

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"

    hexn = ''.join(["%02X" % long(i) for i in ip.split('.')])
    return long(hexn, 16)

def numToDottedQuad(n):
    "convert long int to dotted quad string"
    
    d = 256 * 256 * 256
    q = []
    while d > 0:
        m,n = divmod(n,d)
        q.append(str(m))
        d = d/256

    return '.'.join(q)
    
def makeMask(n):
    "return a mask of n bits as a long integer"

    return (long(2)**n)-1

def ipToNetAndHost(ip, maskbits):
    "returns tuple (network, host) dotted-quad addresses given IP and mask size"

    n = dottedQuadToNum(ip)
    m = makeMask(maskbits)

    host = n & m
    net = n - host

    return (numToDottedQuad(net), numToDottedQuad(host))

An IP address in dotted-quad notation must be converted to an integer to perform bitwise AND and OR operations. In some applications using the decimal integer form may be more convenient or efficient (e.g. storing an IP address in a database).

3 comments

Alex Martelli 22 years, 8 months ago  # | flag

good base idea, but I think it needs enhancements. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66517 for a version of this useful code that uses Python built-in socket and struct modules to avoid "recoding the wheel".

Greg Jorgensen (author) 21 years, 10 months ago  # | flag

recoding the wheel. Alex is right--the Python libraries already have functions to do this.

I wrote these functions as part of explaining IP addresses, dotted-quad notation, and masking to someone. I posted them here more as a learning tool than production code.

Andrey 13 years, 6 months ago  # | flag
def dqn_to_int(st):
    """
    Convert dotted quad notation to integer
    "127.0.0.1" => 2130706433
    """
    st = st.split(".")
    ###
    # That is not so elegant as 'for' cycle and
    # not extensible at all, but that works faster
    ###
    return int("%02x%02x%02x%02x" % (int(st[0]),int(st[1]),int(st[2]),int(st[3])),16)


def int_to_dqn(st):
    """
    Convert integer to dotted quad notation
    """
    st = "%08x" % (st)
    ###
    # The same issue as for `dqn_to_int()`
    ###
    return "%i.%i.%i.%i" % (int(st[0:2],16),int(st[2:4],16),int(st[4:6],16),int(st[6:8],16))
Created by Greg Jorgensen on Sun, 17 Jun 2001 (PSF)
Python recipes (4591)
Greg Jorgensen's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks