Skip to content

Instantly share code, notes, and snippets.

@ndaidong
Last active October 8, 2019 03:49
Show Gist options
  • Save ndaidong/b3c0d6db2eeaac86e2e75b0a3ca56b90 to your computer and use it in GitHub Desktop.
Save ndaidong/b3c0d6db2eeaac86e2e75b0a3ca56b90 to your computer and use it in GitHub Desktop.
Counting number of IP belongs to a subnetmask
#!/usr/bin/env python3
from functools import reduce
from collections import Counter
def ip_count(netmask):
tmp = list(map(lambda x: bin(int(x)), netmask.split('.')))
arr = list(reduce(lambda x, y: x + y, tmp))
counter = Counter(arr)
return counter['1']
@ndaidong
Copy link
Author

ndaidong commented Oct 8, 2019

Usage

examples = [
    '255.255.255.255',
    '255.255.255.8',
    '255.255.255.0',
    '255.255.0.0',
    '255.0.0.0'
]

for ex in examples:
    no = ip_count(ex)
    print(f'Subnetmask {ex} --> No. of IPs {no}')

Result:

Subnetmask 255.255.255.255 --> No. of IPs 32
Subnetmask 255.255.255.8 --> No. of IPs 25
Subnetmask 255.255.255.0 --> No. of IPs 24
Subnetmask 255.255.0.0 --> No. of IPs 16
Subnetmask 255.0.0.0 --> No. of IPs 8

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