Search code examples
python-3.xnetwork-programmingip-addresssubnet

Find the IP Prefix that contains a list of IP addresses


I have a list of IP addresses and I want to find the longest prefix that includes all of those IPs.

This is essentially the opposite of what the hosts function of the ipaddress module does:

https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network.hosts

I scanned the documentation for ipaddress and netaddr and couldn't find anything like that.


Solution

  • I expect you need something like netaddr.spanning_cidr:

    In [1]: from netaddr import spanning_cidr
    
    In [2]: list_of_ips = [
       ...:     '10.0.0.10',
       ...:     '10.0.0.11',
       ...:     '10.0.0.12',
       ...:     '10.0.0.13',
       ...:     '10.0.0.40',
       ...:     '10.0.0.43',
       ...:     '10.0.0.44',
       ...:     '10.0.0.45',
       ...:     '10.0.0.46',
       ...:     '10.0.0.47',
       ...:     '10.0.0.48',
       ...:     '10.0.0.49',
       ...:     '10.0.0.50',
       ...:     '10.0.0.51',
       ...:     '10.0.0.52',
       ...:     '10.0.0.53',
       ...:     '10.0.0.54',
       ...:     '10.0.0.55',
       ...:     '10.0.0.56',
       ...:     '10.0.0.57',
       ...:     '10.0.0.58',
       ...:     '10.0.0.59',
       ...:     '10.0.0.60',
       ...: ]
    
    In [3]: spanning_cidr(list_of_ips)
    Out[3]: IPNetwork('10.0.0.0/26')