Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to break down a IP subnet

I am trying to write a script which breaks down subnets larger(not greater than /16) than /24 to a /24 subnet. Eg : 10.10.10.0/23 should give me 10.10.10.0/24 and 10.10.11.0/24

My logic is to first scan for the CIDR mask. if smaller than 24, then subtract that from 24 and that number(lets say x) gives the total number of /24s and then 1 to third octet of the IP x times and /24.

eg: 10.10.8.0/22

if 22 < 24 
x = 24-22 = 2
total # of /24s = 2^x = 4
So output :
10.10.8.0/24
10.10.9.0/24 
10.10.10.0/24
10.10.11.0/24

I am not sure how to code/modify the string for the third octet only and add 1 to the third octet only.

I am thinking of creating a list of all the third octet values and re constructing the IPs. But if there is a simpler way out there, that would help me a lot !!

Thanks !

like image 707
skd Avatar asked Sep 07 '25 07:09

skd


1 Answers

If you're using Python 3.3 or newer, you can use the ipaddress module. Using the subnets method, you can do it in one line:

>>> list(ipaddress.ip_network('10.10.8.0/22').subnets(new_prefix=24))
[IPv4Network('10.10.8.0/24'), IPv4Network('10.10.9.0/24'), IPv4Network('10.10.10.0/24'), IPv4Network('10.10.11.0/24')]

Converting to strings is trivial. Just cast to str.

like image 126
Carsten Avatar answered Sep 09 '25 04:09

Carsten