Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Breakdown CIDR with netaddr
#1
Was wondering if anyone out here has created an IP based subnet script that will take a CIDR address and then break it down into all the subnets between the CIDR mask and say a /24 Like this: 100.114.208.0/22

This would be the expected output:
100.114.208.0/22
--> 100.114.208.0/23
----> 100.114.208.0/24
----> 100.114.209.0/24
--> 100.114.210.0/23
----> 100.114.210.0/24
----> 100.114.211.0/24
100.114.212.0/22
--> 100.114.212.0/23
----> 100.114.212.0/24
----> 100.114.213.0/24
--> 100.114.214.0/23
----> 100.114.214.0/24
----> 100.114.215.0/24

Below is the code I have so far and I am missing something because the output is incorrect and I can't figure out why...
#!/usr/bin/env python
from netaddr import IPAddress, IPNetwork

def cidr_range(ip, max=24):
    print('Starting subnet: %s/%d' % (ip.ip, ip.prefixlen))
    cidr(ip.ip, ip.prefixlen, max)
def cidr(ip, width, max):
    if width > max:
      return
    print('%s/%d' % (ip, width))
    cidr(ip, width+1, max)
    i = ip.value | (1 << (32-width-1))
    ip2 = IPAddress(i)
    print('%s/%d' % (ip2, width))
    cidr(ip2, width+1, max)
cidr_range(IPNetwork('100.114.208.0/22'))
These are the results I am getting and I am sure it has something to do with how I am recursing, but since I am new to using netaddr and have always been muddy on recursion I can't see what is going wrong.

100.114.208.0/21
100.114.208.0/22
100.114.208.0/23
100.114.208.0/24
100.114.208.128/24
100.114.209.0/23
100.114.209.0/24
100.114.209.128/24
100.114.210.0/22
100.114.210.0/23
100.114.210.0/24
100.114.210.128/24
100.114.211.0/23
100.114.211.0/24
100.114.211.128/24
100.114.212.0/21
100.114.212.0/22
100.114.212.0/23
100.114.212.0/24
100.114.212.128/24
100.114.213.0/23
100.114.213.0/24
100.114.213.128/24
100.114.214.0/22
100.114.214.0/23
100.114.214.0/24
100.114.214.128/24
100.114.215.0/23
100.114.215.0/24
100.114.215.128/24

Any assistance would be appreciated.
TIA
Wally
Reply
#2
I got it working using this:

from netaddr import *
import sys

network_list = []
subnet_list = []

def define_prefixlens(subnet_input, max):
    max_cidr_val = int(max) + 1
    ip = IPNetwork(subnet_input)
    prefixes = (i for i in range(ip.prefixlen +1, max_cidr_val))
    for i in prefixes:
        network_list.append(i)

def list_of_subnets(subnet):
    ip = IPNetwork(subnet)
    for i in network_list:
        sub = ip.subnet(i)
        for i in sub:
           subnet_list.append(i)

def main():
    # value = sys.argv[1]
    value = '10.20.30.0/27'
    # max_cidr = sys.argv[2]
    max_cidr = 24
    define_prefixlens(value, max_cidr)
    # print(network_list)
    list_of_subnets(value)
    for i in sorted(subnet_list):
        print(i)

if __name__ == '__main__':
    main()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020