Last active
February 9, 2024 18:23
-
-
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
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
#!/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) |
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
do you have a version that also works with IPv6 addresses on the list?