Using the ipaddress module that comes with Python3.3+

from ipaddress import IPv4Network, IPv6Network

a = IPv4Network('192.168.0.0/24')
b = IPv4Network('192.168.1.0/24')
c = IPv4Network('127.0.0.1')

x = IPv6Network('2000::/64')
y = IPv6Network('2000:0:0:1::/64')
z = IPv6Network('::1')

# -> https://gist.github.com/pklaus/8f702a6042f8f3fcf7e7
from iphelpers import optimize

nets = [a, b, c]
nets = optimize(nets)
# -> [IPv4Network('127.0.0.1/32'), IPv4Network('192.168.0.0/23')]

netsv6 = [x, y, z]
netsv6 = optimize(netsv6)
# -> [IPv6Network('::1/128'), IPv6Network('2000::/63')]

Resources

Comments