Generating and printing a range of ip addresses

Paul McGuire ptmcg at users.sourceforge.net
Sun Feb 15 21:01:49 EST 2004


"Stephen Briley" <sdb1031 at yahoo.com> wrote in message
news:mailman.26.1076744175.31398.python-list at python.org...
> Hi all,
>
> I would like to write a python script that takes input
> of 2 ip address, one a start address and the other the
> end address and prints a list of all ip address in
> between  in dotted-decimal format.  I've attempted to
> use the ipv4 module
> (http://pynms.sourceforge.net/ipv4.html) ,but I am
> unable to get past this error  "AttributeError: 'str'
> object has no attribute '_address".
>
> Can any suggest a solution to this problem? Is there a
> better way than using the ipv4 module?
>
> Thanks,
>
> Steve
>
Here's a generator function that works with two strings containing valid IP
addresses.
(Note: no error checking, such as verifying that endAddr > startAddr,
endAddr < 255.255.255.255, etc.)

def ipAddrRange(startAddr, endAddr):
    def incrAddr(addrList):
        addrList[3] += 1
        for i in (3,2,1):
            if addrList[i] == 256:
                addrList[i] = 0
                addrList[i-1] += 1

    def asString(addrList):
        return ".".join(map(str,addrList))

    startAddrList = map(int,startAddr.split("."))
    endAddrList = map(int,endAddr.split("."))

    curAddrList = startAddrList[:]
    yield asString(curAddrList)
    for i in range(4):
        while curAddrList[i] < endAddrList[i]:
            incrAddr(curAddrList)
            yield asString(curAddrList)

for addr in ipAddrRange("10.255.255.250","11.0.0.20"):
    print addr





More information about the Python-list mailing list