Production uses 10.42.0.0/23. A disaster recovery site proposes 10.42.1.0/24. The spreadsheet shows two different network addresses. The address plan gives the same space to both teams.
The clue is the /23. It covers everything from 10.42.0.0 through 10.42.1.255, including the entire proposed recovery subnet. The two entries look different because we are comparing the labels instead of the blocks.
Let’s build a Python subnet overlap checker that compares the blocks. It will read an inventory, report duplicates and overlaps, and catch a common input mistake: giving the program a device address when it expects a network prefix.
Turn Each CIDR Prefix Into a Network Object
A CIDR prefix tells you how many leading bits are fixed. A shorter prefix fixes fewer bits and covers more addresses. For IPv4, a /23 covers 512 addresses; a /24 covers 256. Those counts describe the address blocks, regardless of which addresses a particular network uses for hosts. [1]
| Entry | First address | Last address | Relationship to production |
|---|---|---|---|
Production: 10.42.0.0/23 | 10.42.0.0 | 10.42.1.255 | Reference block |
Recovery: 10.42.1.0/24 | 10.42.1.0 | 10.42.1.255 | Contained in production |
Guest Wi-Fi: 10.42.2.0/24 | 10.42.2.0 | 10.42.2.255 | Adjacent; no overlap |
Here is the useful shortcut: two valid CIDR blocks of the same address family are disjoint, equal, or one contains the other. If they share an address, they agree on all the leading bits fixed by the shorter prefix. That is why the entire narrower block falls inside the broader one. There is no need to visit every address to find out. [1, 2]
Python’s standard library provides ip_network() to parse the prefix and .overlaps() to perform the test. [2]
from ipaddress import ip_network
production = ip_network("10.42.0.0/23")
recovery = ip_network("10.42.1.0/24")
guest = ip_network("10.42.2.0/24")
print(production.overlaps(recovery)) # True
print(production.overlaps(guest)) # False
The same method works with IPv6 network objects. Our checker keeps IPv4 and IPv6 separate: it tests overlap between prefixes from the same address family, without trying to translate addresses.
Decide What Counts as Valid Input
What should happen if someone enters 10.42.1.7/24? That is a reasonable way to describe an interface, but it is not the network address of the /24. The last octet contains host bits.
By default, ip_network() rejects that input. Set strict=False and it produces 10.42.1.0/24 by clearing those bits. If you are deliberately importing interface addresses, ip_interface() lets you keep the device address and obtain its network via .network. [2]
For an allocation inventory, we’ll use strict mode. Silently moving an entry to a different starting address can conceal the mistake you wanted to catch. We’ll also require an explicit numeric prefix so a bare address is not silently treated as a /32 or /128.
Build the Python Subnet Overlap Checker
Save this as subnet_overlap_checker.py. It uses the standard library, so there are no packages to install. It reads a UTF-8 text file with one network prefix per line and an optional label after it. Blank lines and lines starting with # are ignored.
import argparse
from ipaddress import ip_network
from itertools import combinations
from pathlib import Path
def read_inventory(lines):
"""Read CIDR prefixes with optional labels."""
entries = []
for number, line in enumerate(lines, start=1):
line = line.strip()
if not line or line.startswith("#"):
continue
fields = line.split(maxsplit=1)
cidr = fields[0]
label = fields[1] if len(fields) == 2 else f"line {number}"
address, slash, prefix = cidr.partition("/")
if not slash or not prefix.isascii() or not prefix.isdecimal():
raise ValueError(f"line {number}: expected an address/prefix")
if "%" in address:
raise ValueError(f"line {number}: omit the IPv6 zone identifier")
try:
network = ip_network(cidr, strict=True)
except ValueError as exc:
raise ValueError(f"line {number}: {exc}") from exc
entries.append((network, label))
if not entries:
raise ValueError("the inventory contains no networks")
return entries
def find_overlaps(entries):
"""Yield each overlapping pair once, in inventory order."""
for (left, left_label), (right, right_label) in combinations(entries, 2):
if left.version != right.version:
continue
if left.overlaps(right):
kind = "DUPLICATE" if left == right else "OVERLAP"
yield f"{kind}: {left_label} ({left}) <-> {right_label} ({right})"
def main():
parser = argparse.ArgumentParser(description="Check a CIDR inventory.")
parser.add_argument("inventory", type=Path, help="UTF-8 text file")
args = parser.parse_args()
try:
with args.inventory.open(encoding="utf-8-sig") as source:
entries = read_inventory(source)
except (OSError, ValueError) as exc:
parser.error(str(exc))
found = False
for report in find_overlaps(entries):
print(report)
found = True
if not found:
print(f"No overlaps found (prefixes checked: {len(entries)}).")
return 1 if found else 0
if __name__ == "__main__":
raise SystemExit(main())
combinations(entries, 2) gives us each pair of rows once, so the program never reports both A versus B and B versus A. The yield statement delivers each finding as the loop discovers it. It does not first build a list of every pair. See our Python generators tutorial for more on how that works. [3]
That does not make the loop cheap for a huge inventory. With n entries, this implementation visits n(n − 1)/2 pairs and skips mixed-family pairs before testing overlap. It retains the inventory in memory, but never expands a prefix into its member addresses. For much larger inventories, group entries by family and address space and consider sorted intervals or a prefix tree. If you need to report every overlapping pair, a dense set of overlaps can still produce a large output.
Run It on a Mixed IPv4 and IPv6 Inventory
Save the following as example_subnets.txt in the same directory. The IPv4 values are in private-use space and the IPv6 values are in the documentation prefix. [4, 5]
# One network prefix per line, followed by an optional label.
10.42.0.0/23 production
10.42.1.0/24 disaster recovery
10.42.2.0/24 guest Wi-Fi
# IPv6 documentation prefixes
2001:db8:42::/48 IPv6 site allocation
2001:db8:42:1::/64 IPv6 lab
From that directory, run:
python3 subnet_overlap_checker.py example_subnets.txt
On Windows, if you use the Python launcher, replace python3 with py -3. The output is:
OVERLAP: production (10.42.0.0/23) <-> disaster recovery (10.42.1.0/24)
OVERLAP: IPv6 site allocation (2001:db8:42::/48) <-> IPv6 lab (2001:db8:42:1::/64)
The guest network doesn’t appear because it starts immediately after the production block ends. The IPv6 lab does appear because its /64 is inside the /48. Copy a valid prefix onto another labeled line and the checker reports that pair as DUPLICATE.
The script exits with 0 for a clean inventory, 1 if it finds overlaps or duplicates, and 2 for invalid or unreadable input. Invalid input stops the check before any result is printed, so an incomplete scan cannot be mistaken for a clean one.
Read an Overlap as a Finding, Not a Verdict
An overlap is a mathematical fact. Whether it is an error depends on what the entries represent.
- Two independent allocations in one address space: an overlap is a reason to investigate. If both teams expect to use the same addresses, settle that before connecting the networks.
- A parent allocation and its child subnet: overlap is expected. The /48 and /64 in the sample illustrate that relationship. Don’t put summary blocks and leaf allocations in the same conflict check unless you intend to review those findings.
- A routing table: a less-specific route and a more-specific route can coexist. Longest-prefix matching is supposed to favor the more-specific applicable route. A default route covers the entire address family, so including it in an allocation check would flag every other prefix. [1]
- Independent routing domains: the same private subnet can be used in separate networks. Audit those domains separately until you plan a connection where their address spaces need to interact. [4]
For a campus network design, a useful first run is one inventory of the actual subnets intended to coexist. Compare the result against the plan before provisioning them.
Once the prefixes are represented as network objects, the overlap test is just one line. The more important decision is which entries should be compared in the first place.
References and Further Reading
- RFC 4632: Classless Inter-domain Routing (CIDR) — IPv4 prefix notation, aggregation, and longest-prefix matching.
- Python 3.12: ipaddress — IPv4/IPv6 Manipulation Library — parsing, strict mode, interface objects, and network overlap checks.
- Python 3.12: itertools.combinations — iteration over pairs without repeating their order.
- RFC 1918: Address Allocation for Private Internets — private IPv4 address space and the implications of connecting independently addressed networks.
- RFC 3849: IPv6 Address Prefix Reserved for Documentation — the
2001:db8::/32documentation block.
