I'm having difficulty using the ipaddress.collapse_addresses()
method.
# n is a list of 192.168.0.0/24 networks (1,2,3,4....etc)
def sumnet():
n = nlist()
for net in n:
snet = ipaddress.collapse_addresses(net)
return snet
I'm only getting back the original list:
Collapsed Networks
[IPv4Network('192.168.0.0/24'), IPv4Network('192.168.1.0/24'),
IPv4Network('192.168.2.0/24'), IPv4Network('192.168.3.0/24'),
IPv4Network('192.168.4.0/24'), IPv4Network('192.168.5.0/24'),
IPv4Network('192.168.6.0/24'), IPv4Network('192.168.7.0/24'),
IPv4Network('192.168.8.0/24')]
Assuming your input is a list of IPv4Networks from ipaddress like...
netlist = [ipaddress.IPv4Network('192.168.0.0/24'),
ipaddress.IPv4Network('192.168.1.0/24'),
ipaddress.IPv4Network('192.168.2.0/24'),
ipaddress.IPv4Network('192.168.3.0/24'),
ipaddress.IPv4Network('192.168.4.0/24'),
ipaddress.IPv4Network('192.168.5.0/24'),
ipaddress.IPv4Network('192.168.6.0/24'),
ipaddress.IPv4Network('192.168.7.0/24'),
ipaddress.IPv4Network('192.168.8.0/24')]
and your desired output is
[IPv4Network('192.168.0.0/21'), IPv4Network('192.168.8.0/24')]
All this can be done with...
import ipaddress
def sumnet(netlist):
return list(ipaddress.collapse_addresses(netlist))
netlist = [ipaddress.IPv4Network('192.168.0.0/24'),
ipaddress.IPv4Network('192.168.1.0/24'),
ipaddress.IPv4Network('192.168.2.0/24'),
ipaddress.IPv4Network('192.168.3.0/24'),
ipaddress.IPv4Network('192.168.4.0/24'),
ipaddress.IPv4Network('192.168.5.0/24'),
ipaddress.IPv4Network('192.168.6.0/24'),
ipaddress.IPv4Network('192.168.7.0/24'),
ipaddress.IPv4Network('192.168.8.0/24')]
print(sumnet(netlist))
The collapse_addresses
method actually takes an entire list of addresses, you don't have to feed it ip_addresses one by one. It will return a generator for the collapsed network, but you can just convert that to a list to deal with it easier.
Let me know if this is not what you were trying to accomplish.
It is a little hard to understand exactly what your code is supposed to do as the following snippet starts a for loop where it grabs the first ip address collapses it into a generator and returns that generator with that single ip address, without looking at any of the other ip addresses. This however doesn't seem to be consistent with what your question claims the output to be.
for net in n:
snet = ipaddress.collapse_addresses(net)
return snet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With