Skip to content

Instantly share code, notes, and snippets.

@nicholasren
Created September 5, 2019 13:28
Show Gist options
  • Save nicholasren/a8281581e5e2932166e8728cffa1982d to your computer and use it in GitHub Desktop.
Save nicholasren/a8281581e5e2932166e8728cffa1982d to your computer and use it in GitHub Desktop.
cidr to ip range
#!/usr/bin/env python
# range_of.py 10.0.0.0/8
import sys
# Get address string and CIDR string from command line
(addrString, cidrString) = sys.argv[1].split('/')
# Split address into octets and turn CIDR into int
addr = addrString.split('.')
cidr = int(cidrString)
# Initialize the netmask and calculate based on CIDR mask
mask = [0, 0, 0, 0]
for i in range(cidr):
mask[i/8] = mask[i/8] + (1 << (7 - i % 8))
# Initialize net and binary and netmask with addr to get network
net = []
for i in range(4):
net.append(int(addr[i]) & mask[i])
# Duplicate net into broad array, gather host bits, and generate broadcast
broad = list(net)
brange = 32 - cidr
for i in range(brange):
broad[3 - i/8] = broad[3 - i/8] + (1 << (i % 8))
net_mask = ".".join(map(str, mask))
from_ip = ".".join(map(str, net))
to_ip = ".".join(map(str, broad))
# Print information, mapping integer lists to strings for easy printing
print "Range: " , "%s - %s" % (from_ip, to_ip)
print "Netmask: " , net_mask
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment