-
-
Save ldong/487aa2461450e4dd15607ba8dfcd846e to your computer and use it in GitHub Desktop.
Python script to calculate CIDR values
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
""" Calculate the subnet mask, its binary representation, number of host and | |
network bits, and the total number of hosts for a given CIDR address. | |
Usage: python cidr.py [cidr] | |
Notes: Pipe the command to jq to pretty print the JSON. Python 2 or 3 compatible. | |
Examples: | |
python cidr.py 10.0.0.0/24 | |
python cidr.py 172.0.0.0/16 | jq | |
""" | |
from __future__ import print_function | |
import json | |
import re | |
import sys | |
def netmask(cidr): | |
# Regex to represent valid CIDR notation | |
valid_ip = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/([0-3]?[0-9])$" | |
# verify that the user entered a valid CIDR range | |
if not re.match(valid_ip, cidr): | |
return json.dumps({'error': 'Invalid IP address'}) | |
net_bits = int(cidr[cidr.find('/')+1:]) | |
num_host_bits = 32 - net_bits | |
addr_bits = list(('1'*int(net_bits)).zfill(32)) | |
addr_bits.reverse() | |
host_bits = "".join(addr_bits) | |
num_hosts = 2**num_host_bits | |
mask_vals = [128, 64, 32, 16, 8, 4, 2, 1] | |
# how many full octets do we have | |
full_octets = int(net_bits/8) | |
netmask = '255.' * full_octets | |
remaining_bits = net_bits - (full_octets*8) | |
if remaining_bits > 0: | |
mask = sum(mask_vals[:remaining_bits]) | |
netmask = netmask + str(mask) + '.' | |
netmask = netmask + '0.' * abs((4-(len(netmask.split('.'))-1))) | |
# chop off the trailing decimal | |
netmask = netmask[:-1] | |
# return JSON with all this | |
d = {'cidr': cidr, | |
'netmask': netmask, | |
'netmask_binary': host_bits, | |
'num_hosts': num_hosts, | |
'network_bits': net_bits, | |
'host_bits': num_host_bits, | |
} | |
return json.dumps(d) | |
if __name__ == '__main__': | |
usage = """ | |
Calculate the subnet mask, its binary representation, number of host and network bits, | |
and the total number of hosts for a given CIDR address. | |
Usage: python cidr.py [cidr] | |
Notes: Pipe the command to jq to pretty print the JSON. Python 2 or 3 compatible. | |
Examples: | |
python cidr.py 10.0.0.0/24 | |
python cidr.py 172.0.0.0/16 | jq | |
""" | |
try: | |
input = sys.argv[1] | |
mask = netmask(input) | |
print(mask) | |
except IndexError: | |
print(usage) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment