Skip to content

Instantly share code, notes, and snippets.

@vndmtrx
Last active October 18, 2023 20:09
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save vndmtrx/dc412e4d8481053ddef85c678f3323a6 to your computer and use it in GitHub Desktop.
Save vndmtrx/dc412e4d8481053ddef85c678f3323a6 to your computer and use it in GitHub Desktop.
Python 3 simple subnet calculator
#!/usr/bin/env python3
# Use: ./subnet.py <ip/cidr>
# Alt: ./subnet.py <ip> <mask>
import sys
if __name__=="__main__":
addr = [0, 0, 0, 0]
mask = [0, 0, 0, 0]
cidr = 0
if len(sys.argv) == 2:
(addr, cidr) = sys.argv[1].split('/')
addr = [int(x) for x in addr.split(".")]
cidr = int(cidr)
mask = [( ((1<<32)-1) << (32-cidr) >> i ) & 255 for i in reversed(range(0, 32, 8))]
elif len(sys.argv) == 3:
addr = sys.argv[1]
mask = sys.argv[2]
addr = [int(x) for x in addr.split(".")]
mask = [int(x) for x in mask.split(".")]
cidr = sum((bin(x).count('1') for x in mask))
else:
print("Use: {0} <ip/cidr>".format(sys.argv[0]))
print("Alt: {0} <ip> <mask>".format(sys.argv[0]))
sys.exit(-1)
netw = [addr[i] & mask[i] for i in range(4)]
bcas = [(addr[i] & mask[i]) | (255^mask[i]) for i in range(4)]
print("Address: {0}".format('.'.join(map(str, addr))))
print("Mask: {0}".format('.'.join(map(str, mask))))
print("Cidr: {0}".format(cidr))
print("Network: {0}".format('.'.join(map(str, netw))))
print("Broadcast: {0}".format('.'.join(map(str, bcas))))
@plambrechtsen
Copy link

Thanks for this code, I used it here for creating a CIDR -> Netmask map when parsing Azure IPs and converting them into subnet masks needed by Cisco: https://gist.github.com/plambrechtsen/ca0a08d947c7f5dac6ed85805616105b

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