Created
August 24, 2012 08:47
-
-
Save xhochy/3447675 to your computer and use it in GitHub Desktop.
Calculate free ranges of an IPv4Network
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
blocked_ips = [ipv4Network[0], ipv4Router] | |
ranges = [[ipv4Network[1], ipv4Network[-1]]] | |
for ip in blocked_ips: | |
index = 0 | |
# Find range which includes the ip, i.e. 'start <= ip <= end' | |
while (index < len(ranges)) and (not ((ranges[index][0] <= ip) and (ip <= ranges[index][1]))): | |
index += 1 | |
if index == len(ranges): | |
# IP address is already excluded | |
pass | |
else: | |
if ip == ranges[index][0]: | |
if ip == ranges[index][1]: | |
# The IP is already in an alone range, so just delete this range | |
ranges.pop(index) | |
else: | |
# ip < ranges[index][1] | |
ranges[index][0] = ip + 1 | |
else: | |
# ranges[index][0] < ip | |
if ip == ranges[index][1]: | |
# just remove the last ip | |
ranges[index][1] = ip - 1 | |
else: | |
# ip is located inside a range, so split this range | |
old_range_end = ranges[index][1] | |
ranges[index][1] = ip - 1 | |
ranges.insert(index + 1, [ip + 1, old_range_end]) | |
for range in ranges: | |
print(' range {0} {1};'.format(range[0], range[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment