Monday, February 23, 2009

Generating and printing a range of ip addresses

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

No comments: