Skip to content

Instantly share code, notes, and snippets.

@leonjza
Forked from joswr1ght/countips.py
Created August 24, 2022 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonjza/a6150a990395d3293f774c74a7634a21 to your computer and use it in GitHub Desktop.
Save leonjza/a6150a990395d3293f774c74a7634a21 to your computer and use it in GitHub Desktop.
Read a file of network + CIDR masks, one per line; count the number of IP addresses it represents
#!/usr/bin/env python3
#
# original: https://gist.github.com/joswr1ght/595d49d5a7914cf7305b73512f37186a
import sys
def countips(netblock):
v = netblock.split('/')
# nothing?
if len(v) <= 0:
return 0
# no /subnet
if len(v) == 1:
v.append(32)
_, cidr = v
return 2**(32 - int(cidr))
if __name__ == '__main__':
if len(sys.argv) != 2:
print(f'Usage: {sys.argv[0]} <file with CIDR masks>')
sys.exit(0)
ipcount = 0
with open(sys.argv[1]) as infile:
for netblock in infile:
ipcount += countips(netblock)
print(ipcount)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment