Last active
August 17, 2017 10:26
-
-
Save pavdmyt/733b62fe517c467110d07c40e360df64 to your computer and use it in GitHub Desktop.
[Python] Print all valid IPv4 netmasks in dot-decimal notation.
This file contains 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
# -*- coding: utf-8 -*- | |
""" | |
Print all valid IPv4 netmasks in dot-decimal notation. | |
Netmask reference chart: | |
http://unixwiz.net/techtips/netmask-ref.html | |
""" | |
def ipv4_netmask_gen(): | |
"""Generator that returns a valid dot-decimal IPv4 netmasks.""" | |
def slice_(bits): | |
assert len(bits) == 32 | |
return bits[0:8], bits[8:16], bits[16:24], bits[24:32] | |
ones, zeros = 0, 32 | |
base = '0' * zeros | |
while base != '1' * 33: | |
quads = [str(int(quad, base=2)) for quad in slice_(base)] | |
yield '.'.join(quads) | |
ones += 1 | |
zeros -= 1 | |
base = '1' * ones + '0' * zeros | |
def main(): | |
for netmask in ipv4_netmask_gen(): | |
print(netmask) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment