Skip to content

Instantly share code, notes, and snippets.

@toringe
Created October 22, 2015 10:28
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save toringe/f2af77fe49d3a52fc136 to your computer and use it in GitHub Desktop.
Save toringe/f2af77fe49d3a52fc136 to your computer and use it in GitHub Desktop.
Merge CIDR blocks into super blocks if possible
#!/usr/bin/env python
#
# Example 1: All blocks in list.txt, one CIDR per line
# cat list.txt | cidr.py
#
# Example 2: Echo CIDR blocks to stdout
# echo 1.2.3.0/25 1.2.3.128/25 | cidr.py
import sys
from netaddr import *
# Read from stdin
data = sys.stdin.readlines()
if len(data) == 1:
# Input from echo
data = data[0].split()
# Create an IPSet of the CIDR blocks
# IPSet automatically runs cidr_merge
nets = IPSet(data)
# Output the superset of CIDR blocks
for cidr in nets.iter_cidrs():
print cidr
@israelfaria
Copy link

Good thing about gists we relay into the wild is how useful they can be for someone else entirely years later. Hit this lovely simple solution, cloned, 3m later problem solved.

Thank you.

@toringe
Copy link
Author

toringe commented Feb 6, 2022

My pleasure 🤩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment