Python 3: create a list of possible ip addresses from a CIDR notation Python 3: create a list of possible ip addresses from a CIDR notation python python

Python 3: create a list of possible ip addresses from a CIDR notation


In Python 3 as simple as

>>> import ipaddress>>> [str(ip) for ip in ipaddress.IPv4Network('192.0.2.0/28')]['192.0.2.0', '192.0.2.1', '192.0.2.2','192.0.2.3', '192.0.2.4', '192.0.2.5','192.0.2.6', '192.0.2.7', '192.0.2.8','192.0.2.9', '192.0.2.10', '192.0.2.11','192.0.2.12', '192.0.2.13', '192.0.2.14','192.0.2.15']


If you aren't married to using the built-in module, there is a project called netaddr that is the best module I have used for working with IP networks.

Have a look at the IP Tutorial which illustrates how easy it is working with networks and discerning their IPs. Simple example:

>>> from netaddr import IPNetwork>>> for ip in IPNetwork('192.0.2.0/23'):...    print '%s' % ip...192.0.2.0192.0.2.1192.0.2.2192.0.2.3...192.0.3.252192.0.3.253192.0.3.254192.0.3.255


I would prefer to do a little math rather than to install an external module, no one has the same taste with me?

#!/usr/bin/env python# python cidr.py 192.168.1.1/24import sys, struct, socket(ip, cidr) = sys.argv[1].split('/')cidr = int(cidr) host_bits = 32 - cidri = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endiannessstart = (i >> host_bits) << host_bits # clear the host bitsend = start | ((1 << host_bits) - 1)# excludes the first and last address in the subnetfor i in range(start, end):    print(socket.inet_ntoa(struct.pack('>I',i)))