Created
October 6, 2012 20:58
-
-
Save freddyb/3846097 to your computer and use it in GitHub Desktop.
python iterator that returns IP addresses (as strings) for given ip/cidr string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class cidrator(): | |
def __init__(self, mask ="192.168.1.1/16", skip255=True, skip0=True): | |
self.skip255 = skip255 | |
self.skip0 = skip0 | |
addr, rng = mask.split("/") | |
addr_int = sum((256**(3-i) * int(b)) for i,b in enumerate(addr.split ("."))) | |
self.start = addr_int & int("0b"+("1"*int(rng)) + "0"*(32-int(rng)),2) | |
self.stop = addr_int | int("0b"+("0"*int(rng)) + "1"*(32-int(rng)),2) | |
self.current = self.start | |
def int2ipstr(self, s): | |
s = hex(s)[2:] | |
return '.'.join(('%s' % int(x,16) for x in (s[i:2+i] for i in xrange(0,8,2)))) | |
def ipstr2int(self, addr): | |
return | |
def __iter__(self): | |
return self | |
def next(self): | |
if self.current > self.stop: | |
raise StopIteration | |
else: | |
self.current += 1 | |
res = self.int2ipstr(self.current - 1) | |
if res.endswith(".0") and self.skip0: | |
res = self.next() | |
if res.endswith('.255') and self.skip255: | |
res = self.next() | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
for ip in cidrator("172.16.0.0/12"): print ip
It's an iterator, that means you never have to sore the actual list of all IP addresses in memory :)