Skip to content

Instantly share code, notes, and snippets.

@sulrich
Created March 21, 2022 18:12
Show Gist options
  • Save sulrich/9cdfa3c6cbcfe7038e743f4fdf48510c to your computer and use it in GitHub Desktop.
Save sulrich/9cdfa3c6cbcfe7038e743f4fdf48510c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import radix
import ipaddress
rtree = radix.Radix()
test_addrs = [
"10.0.0.0/24",
"10.0.1.0/24", # should form a /23 w/the above
"10.0.1.0/28", # should be covered by previous
"10.1.0.0/16",
"10.1.0.1/32", # should be covered by previous
"20.20.0.0/24", # never aggregated
]
for a in test_addrs:
rtree.add(a)
super_rtree = radix.Radix()
for pref in rtree:
agg_pref = rtree.search_worst(pref.prefix)
if agg_pref.prefix == pref.prefix:
super_rtree.add(pref.prefix)
print("covering consolidation")
for agg in super_rtree:
print(agg.prefix)
adj_tree = radix.Radix()
for adj in super_rtree:
# get the supernet for this prefix
supernet = str(ipaddress.ip_network(adj.prefix).supernet())
# check to see if there are other/adjacent nets in this supernet
member_check = super_rtree.search_covered(supernet)
if len(member_check) == 2:
if member_check[0].prefixlen == member_check[1].prefixlen == adj.prefixlen:
adj_tree.add(supernet)
else:
adj_tree.add(adj.prefix)
else:
adj_tree.add(adj.prefix)
print("match consolidation")
for pref in adj_tree:
print(pref.prefix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment