Skip to content

Instantly share code, notes, and snippets.

@moshekaplan
Last active January 1, 2016 15:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moshekaplan/8167877 to your computer and use it in GitHub Desktop.
Save moshekaplan/8167877 to your computer and use it in GitHub Desktop.
CIDR to IPv4 converter. Thrown together for corelanc0d3r.
# CIDR to ipv4
# Written by Moshe Kaplan
def to_long(ip):
ip = ip.split('.', 4)
return int(ip[0])*(2**24) + int(ip[1])*(2**16) + int(ip[2])*(2**8) + int(ip[3])
def to_dotted_decimal(long_form):
octets = []
for i in range(4):
octets += [str(long_form % 2**8)]
long_form = long_form >> 8
return '.'.join(octets[::-1])
def cidr_to_ipv4(cidr):
# Takes a CIDR address: 192.168.2.0/24 and returns a list of IP's in it
ip, network_bits = cidr.split('/',1)
host_bits = 32 - int(network_bits)
# Simplest approach: Turn it into a long, zero out the host bits and then iterate
long_form = to_long(ip)
# zero out the host bits
start = (long_form >> host_bits) << host_bits
for i in xrange(2**host_bits):
yield to_dotted_decimal(start | i)
for ip in cidr_to_ipv4("192.168.2.0/25"):
print ip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment