Skip to content

Instantly share code, notes, and snippets.

@joswr1ght
Last active February 9, 2024 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joswr1ght/595d49d5a7914cf7305b73512f37186a to your computer and use it in GitHub Desktop.
Save joswr1ght/595d49d5a7914cf7305b73512f37186a 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 python
import sys
def countips(netblock):
cidr = int(netblock.split('/')[1])
return 2**(32 - cidr)
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)
@gracino
Copy link

gracino commented Feb 9, 2024

do you have a version that also works with IPv6 addresses on the list?

@gracino
Copy link

gracino commented Feb 9, 2024

This is what I came up with to account for IP lists that may or may not have the /32 and if the /is greater than 32 for IPv6 addresses

#!/usr/bin/env python3
import sys

def countips(netblock):
slash = netblock.find("/")
if slash != -1:
cidr = int(netblock.split('/')[1])
else:
cidr = 32
if cidr > 32:
return 2**(128 - cidr)
else:
return 2**(32 - cidr)

if (len(sys.argv) != 2):
print(f"Usage: {sys.argv[0]} ")
sys.exit(0)

ipcount=0
with open(sys.argv[1]) as infile:
for netblock in infile:
ipcount += countips(netblock)
print(f'{ipcount:,}')

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