Skip to content

Instantly share code, notes, and snippets.

@pavdmyt
Last active August 17, 2017 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavdmyt/733b62fe517c467110d07c40e360df64 to your computer and use it in GitHub Desktop.
Save pavdmyt/733b62fe517c467110d07c40e360df64 to your computer and use it in GitHub Desktop.
[Python] Print all valid IPv4 netmasks in dot-decimal notation.
# -*- 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