Wednesday, July 29, 2009

Iterating over a sequence of IPs in Python

I was bit bored, so I wrote a simple iterator that iterates over a sequence of IPs using a subnet bitmask.

import struct
import socket

class IPIterator:
def __init__(self, ip, bitmask):
self.ip = ip
self.bitmask = bitmask
def __iter__(self):
ipnum = struct.unpack(">L", socket.inet_aton(self.ip))[0]
mask = 2 ** self.bitmask - 1
for x in xrange(ipnum & ~mask, ipnum | mask):
yield socket.inet_ntoa(struct.pack(">L", x))

if __name__ == "__main__":
for x in IPIterator("1.2.3.4", 8):
print x