Skip to content
Python: Collapse IP networks without filling gaps

Python: Collapse IP networks without filling gaps

November 26, 2026

ipaddress.collapse_addresses() combines networks while preserving their combined address coverage. A gap between networks must stay a gap; replacing every input with one broad enclosing subnet can include addresses you did not select.

Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.

Run the example

Save this as network_collapse.py in an empty working directory:

from ipaddress import collapse_addresses, ip_address, ip_network

networks = [ip_network(text) for text in (
    "192.0.2.0/26", "192.0.2.64/26", "192.0.2.192/26"
)]
collapsed = list(collapse_addresses(networks))
original = {address for network in networks for address in network}
result = {address for network in collapsed for address in network}
assert original == result
print("Collapsed:", [str(network) for network in collapsed])
print("Address count:", len(result))
print("Gap address included:", ip_address("192.0.2.128") in result)

Run it without -O so any assertions remain enabled:

python3 network_collapse.py

Captured output:

Collapsed: ['192.0.2.0/25', '192.0.2.192/26']
Address count: 192
Gap address included: False

The two adjacent /26 networks become one /25. The third stays separate because the intervening /26 was never included. The set equality assertion checks the entire small example, including network and broadcast addresses.

Limits and cleanup

The example uses documentation addresses and makes no network requests. Enumerating addresses is practical only for this tiny check; do not build sets for large IPv4 or IPv6 ranges. Collapse IPv4 and IPv6 inputs separately because mixing their network types raises TypeError.

After testing, remove the example script from its working directory:

rm -- network_collapse.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on