Collapse – collapsing ip systems with python ipaddress module – stack overflow
Presuming your input is a summary of IPv4Networks from ipaddress like…
netlist = [ipaddress.IPv4Network(‘192.168../24’),
ipaddress.IPv4Network(‘192.168.1./24’),
ipaddress.IPv4Network(‘192.168.2./24’),
ipaddress.IPv4Network(‘192.168.3./24’),
ipaddress.IPv4Network(‘192.168.4./24’),
ipaddress.IPv4Network(‘192.168.5./24’),
ipaddress.IPv4Network(‘192.168.6./24’),
ipaddress.IPv4Network(‘192.168.7./24’),
ipaddress.IPv4Network(‘192.168.8./24’)]
as well as your preferred output is
[IPv4Network(‘192.168../21’), IPv4Network(‘192.168.8./24’)]
All you can do this with…
import ipaddress
def sumnet(netlist):
return list(ipaddress.collapse_addresses(netlist))
netlist = [ipaddress.IPv4Network(‘192.168../24’),
ipaddress.IPv4Network(‘192.168.1./24’),
ipaddress.IPv4Network(‘192.168.2./24’),
ipaddress.IPv4Network(‘192.168.3./24’),
ipaddress.IPv4Network(‘192.168.4./24’),
ipaddress.IPv4Network(‘192.168.5./24’),
ipaddress.IPv4Network(‘192.168.6./24’),
ipaddress.IPv4Network(‘192.168.7./24’),
ipaddress.IPv4Network(‘192.168.8./24’)]
print(sumnet(netlist))
The collapse_addresses method really takes a whole listing of addresses, it’s not necessary to feed it ip_addresses one at a time. It’ll return an electrical generator for that collapsed network, but you can easily convert that to some list to cope with it simpler.
Tell me if this isn’t that which you were attempting to accomplish.
It’s a little confusing precisely what your code should really do because the following snippet starts a for loop where it grabs the very first ip collapses it right into a generator and returns that generator with this single ip, without searching at the other ip addresses. Nevertheless this does not appear to become in line with what your question claims the output to become.
for internet in n:
snet = ipaddress.collapse_addresses(internet)
return snet
Resourse: https://stackoverflow.com/questions/57382997/