I think the following approach should be quite effective:
import netaddr
import bisect
def subnets_overlap(subnets):
ranges = []
for subnet in subnets:
first = bisect.bisect_left(ranges, subnet.first)
last = bisect.bisect_right(ranges, subnet.last)
if first != last or first % 2 == 1:
return True
ranges[first:first] = [subnet.first, subnet.last]
return False
Examples:
>>> subnets_overlap([netaddr.IPNetwork('1.0.0.0/24'), netaddr.IPNetwork('1.0.0.252/30')])
True
>>> subnets_overlap([netaddr.IPNetwork('1.0.0.0/24'), netaddr.IPNetwork('1.0.1.0/24')])
False
source
share