Created
May 12, 2018 00:54
-
-
Save zhehaowang/17c40c6f35c54c8ebc8e902a8b812cce to your computer and use it in GitHub Desktop.
IP prefix within range
This file contains hidden or 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
#!/usr/local/bin/python3 | |
def ipPrefixRange(addr, start, end): | |
""" | |
@param addr valid String of ip address e.g. 192.168.0.0/16 | |
@param start int range to start iteration from | |
@param end int range to end the iteration with | |
@return [String] list of string of possible prefixes between start and end | |
""" | |
assert start <= end | |
addrs = addr.split('/') | |
ipAddr = ipStrToInt(addrs[0]) | |
prefix = int(addrs[1]) | |
assert prefix <= start | |
result = [] | |
idx = start | |
while idx <= end: | |
for i in range(2 ** (idx - prefix)): | |
result.append(ipIntToStr(ipAddr + (i << (32 - idx))) + "/" + str(idx)) | |
idx += 1 | |
return result | |
def ipIntToStr(ipInt): | |
res = str(ipInt % 256) | |
ipInt //= 256 | |
res = str(ipInt % 256) + '.' + res | |
ipInt //= 256 | |
res = str(ipInt % 256) + '.' + res | |
ipInt //= 256 | |
res = str(ipInt % 256) + '.' + res | |
return res | |
def ipStrToInt(ipStr): | |
ips = ipStr.split('.') | |
assert len(ips) == 4 | |
return (int(ips[0]) << 24) + (int(ips[1]) << 16) + (int(ips[2]) << 8) + int(ips[3]) | |
if __name__ == "__main__": | |
# print(ipIntToStr(ipStrToInt('0.0.0.1')) == '0.0.0.1') | |
# print(ipIntToStr(ipStrToInt('192.168.64.129')) == '192.168.64.129') | |
# print(ipPrefixRange('192.168.0.0/16', 18, 18)) | |
# print(ipPrefixRange('192.168.0.0/16', 16, 17)) | |
# print(ipPrefixRange('192.168.0.0/16', 16, 18)) | |
print(ipPrefixRange('192.168.0.0/16', 18, 20)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment