-
-
Save vimagick/d4e1ebb1bdd3c3190fbdd1d326a7b312 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
# | |
# CIDR calculator: find the minimum CIDR which contains multiple ip addresses | |
# | |
# Example: | |
# $ cidr 142.250.66.78 142.250.204.142 142.251.130.14 | |
# 142.250.0.0/15 | |
# | |
import os | |
import sys | |
comm = os.path.commonprefix(['.'.join(['{:08b}'.format(int(i)) for i in ip.split('.')]) for ip in sys.argv[1:]]).rstrip('.') | |
addr = '.'.join(([str(int('{:0<8s}'.format(i), 2)) for i in comm.split('.')] + ['0']*4)[:4]) | |
bits = sum(len(i) for i in comm.split('.')) | |
cidr = '{}/{}'.format(addr, bits) | |
print(cidr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment