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


Messages In This Thread
Breakdown CIDR with netaddr - by wfsteadman - Oct-05-2019, 04:26 PM
RE: Breakdown CIDR with netaddr - by wfsteadman - Oct-06-2019, 06:22 PM

Forum Jump:

User Panel Messages

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