IP address conversion functions with the builtin socket module

Convert dotted-quad IP addresses to long integer and back, get network and host portions from an IP address, all nice and fast thanks to the builtin socket module (with a little help from the builtin struct module, too).

# IP address manipulation functions, dressed up a bit

import socket, struct

def ipToNum(ip):
    return struct.unpack('!I', socket.inet_aton(ip))[0]

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def numToDottedQuad(n):
    "convert long int to dotted quad string"
    return socket.inet_ntoa(struct.pack('L',n))
      
def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1)-1

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

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

 

from http://code.activestate.com/recipes/65219-ip-address-conversion-functions/

 

posted on 2012-08-16 01:12  Xingning Ou  阅读(134)  评论(0编辑  收藏  举报

导航