Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have been handed the task of creating a function in python (3.1) that will take a CIDR notation and return the list of possible ip addresses. I have looked around python.org and found this: http://docs.python.org/dev/py3k/library/ipaddr.html

but i haven't seen anything that will fill this need... I would be very grateful for any assistance anyone cares to kick my way. thanks in advance. :-)

like image 621
MadSc13ntist Avatar asked Dec 21 '09 19:12

MadSc13ntist


People also ask

How do I find out how many IP addresses are in CIDR?

How many addresses does a CIDR block represent? You calculate 2 32-prefix , where prefix is the number after the slash. For example, /29 contains 232-29=23=8 addresses.

How do I use CIDR block notation?

In CIDR notation, IP addresses are written as a prefix, and a suffix is attached to indicate how many bits are in the entire address. The suffix is set apart from the prefix with a slash mark. For instance, in the CIDR notation 192.0. 1.0/24, the prefix is 192.0.

What is CIDR notation with example?

CIDR (Classless Inter-Domain Routing) notation is a compact method for specifying IP addresses and their routing suffixes. For example, we can express the idea that the IP address 192.168. 0.1 is associated with the netmask 255.255. 255.0 by using the CIDR notation of 192.168.


2 Answers

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'] 
like image 188
Petr Javorik Avatar answered Sep 20 '22 23:09

Petr Javorik


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.0 192.0.2.1 192.0.2.2 192.0.2.3 ... 192.0.3.252 192.0.3.253 192.0.3.254 192.0.3.255 
like image 25
jathanism Avatar answered Sep 21 '22 23:09

jathanism