playing with IP's

Darrell news at dorb.com
Sat Mar 3 09:29:10 EST 2001


"Langa Kentane" wrote:
> Greetings.
> Here is what I wanna do:
> Given a network number and mask ie:
> 192.168.1.0/32
> I want to create a list with all the valid hosts on that range.
> Problem is I don't know how to play with decimal.
>
> Where would I start.. any sample code?
> Thanks
>
I don't know a lot about this, but here's a starting point.
Be sure to post any improvements :)
It might be handy to print out the subnet boundary's.

--Darrell

#!/usr/bin/env python
import re

def shiftOctents(octents):
    """
    Convert dot separated IP format to a number
    This might exist in the socket module?
    """
    octents=octents.split(".")
    octents.reverse()
    v=0
    for x in range(len(octents)):
        v|= int(octents[x]) << (x*8)
    return v

    # Bytes used for local addresses in a class of IP
_netWorkClassDict={'a':3, 'b':2, 'c':1}

def getValues(input, netWorkClass='b'):
    """
    Return IP converted to a number
    subnet address size
    host address size
    """
    netWorkClass=netWorkClass.lower()

    ip, mask = input.split("/")
    mask = shiftOctents(mask)
    hosts = ~mask & 0xffffffffL -1

    val='0x'+'ff'*_netWorkClassDict[netWorkClass]
    netWorkClassMask = int(val, 16)
    subnet=max(0, (netWorkClassMask/(hosts+2)) -1)

    ip= shiftOctents(ip)
    return ip, subnet, hosts

def backToDotNotation(val):
    res=[]
    tempVal=val
    for x in range(4):
        res.append(tempVal & 0xff)
        tempVal = tempVal >> 8
    res.reverse()
    return "%d.%d.%d.%d"%tuple(res)

def test1():
    input=["192.168.1.0/255.255.0.0","192.168.1.0/255.255.240.0",
    "192.168.1.0/255.255.254.0","192.168.1.0/255.255.255.252"
    ]
    expected=[(0, 65534), (14, 4094),(126, 510), (16382, 2)]

    netWorkClass='b'
    for ix in range(len(input)):
        i=input[ix]
        print "Using:", i
        print "Class:", netWorkClass
        values=getValues(i, netWorkClass)
        assert(values[1:]==expected[ix])
        print 'Number of hosts for this subnet:', values[2]
        print 'Ending IP for this subnet:', backToDotNotation(values[0] |
values[2])
        print 'Number of subnets:', values[1]
        print

test1()






More information about the Python-list mailing list