summarizing adjacent subnets with python netaddr cidr_merge

Question:

I have a list of IPNetworks that will not merge with netaddr.cidr_merge even though some are adjacent. Am I doing something wrong?

>>> from netaddr import IPNetwork, cidr_merge
>>> iplist = [
         IPNetwork('10.105.205.8/29'), 
         IPNetwork('10.105.205.16/28'), 
         IPNetwork('10.105.205.32/27'), 
         IPNetwork('10.105.205.64/26'), 
         IPNetwork('10.105.205.128/26'),
         IPNetwork('10.105.205.192/28'),
         IPNetwork('10.105.205.208/29'),
         IPNetwork('10.105.206.48/28'),
         IPNetwork('10.105.206.80/28')
    ]
>>> summary = cidr_merge(iplist)
>>> summary == iplist
    True

I’m using Python 3.3.4 and netaddr 7.12 on Mac OSX 10.8.5.

Asked By: Ghost

||

Answers:

netaddr is working correctly here. Not all adjacent subnets can be summarized.

For instance, consider the subnets 10.255.255.0/24 and 11.0.0.0/24. While they are adjacent — the first one ends with 10.255.255.255, and the second begins with 11.0.0.0 — they cannot be summarized, as they cross a boundary that is much larger than either of these two networks.

Additionally, regardless of how they are aligned, two adjacent networks can only be joined together if they’re of equal size. Mismatched sizes cannot be combined into a single range, because the size of the combined network will not be a power of 2.

Answered By: user149341

@duskwuff –

Thank you for your reply. I agree with the first part but the second…I think I know where your going with it, but it’s not 100% accurate. For instance if I take an edited list from above, and append 10.105.205.0/29. The subnets will summarize to a /25. Yes they must be a power of 2, but all parts of the whole subnet must be present before netaddr will summarize, regardless if they are of equal size.

   iplist =[
        IPNetwork('10.105.205.8/29'), 
        IPNetwork('10.105.205.16/28'), 
        IPNetwork('10.105.205.32/27'), 
        IPNetwork('10.105.205.64/26'),
        ]
    >>> iplist.append(IPNetwork('10.105.205.0/29'))
    >>> netaddr.cidr_merge(iplist)
        [IPNetwork('10.105.205.0/25')]
Answered By: Ghost
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.