Soviero
Soviero

Reputation: 1902

Get a list of subnets matching a given CIDR

I'm trying to take a known subnet ID and CIDR mask, e.g., 10.0.0.0/22, and get a list like this:

[('10.0.0.0', '10.0.3.255'),
('10.0.4.0', '10.0.7.255'),
...
('10.255.252.0', '10.255.255.255')]

I've tried a few existing modules like ipcalc, but it doesn't seem to have a feature like that. I'm not sure what kind of math is necessary for me to write my own module to do it, either.

Upvotes: 2

Views: 1299

Answers (2)

falsetru
falsetru

Reputation: 369424

You can use ipaddress module if you use Python 3.3+:

>>> import ipaddress
>>> it = ipaddress.ip_network('10.0.0.0/8').subnets(new_prefix=22)
>>> networks = [(str(n.network_address), str(n.broadcast_address)) for n in it]
>>> len(networks)
16384
>>> networks[0]
('10.0.0.0', '10.0.3.255')
>>> networks[-1]
('10.255.252.0', '10.255.255.255')

In Python 2.x, use ipaddr:

>>> import ipaddr
>>> it = ipaddr.IPNetwork('10.0.0.0/8').subnet(new_prefix=22)
>>> networks = [(str(n.network), str(n.broadcast)) for n in it]
>>> len(networks)
16384
>>> networks[0]
('10.0.0.0', '10.0.3.255')
>>> networks[-1]
('10.255.252.0', '10.255.255.255')

UPDATE

There's Python 2.7 backport of Python 3.3 ipaddress: py2-ipaddress.

Upvotes: 5

Use the new ipaddress module in Python 3.3:

import ipaddress

for i in ipaddress.ip_network('10.0.0.0/8').subnets(new_prefix=22):
    print(i)

Upvotes: 5

Related Questions