Tidy Desk Digital · Free tools

Compare two IPv4 range lists

Find where two saved address-allocation lists overlap and count the shared addresses once, without contacting a network or generating every address. This compares ranges, not firewall rules.

Use Python 3.10 or later. No extra packages. All examples below are fictional.

Start with the example files

Download the range-overlap checker and exercises (ZIP). It includes the complete program, three fictional lists, README, MIT licence and tests. Extract everything into a new folder and review the code before running it.

1. Know what a range means

Internet Protocol version 4 (IPv4) addresses have four dot-separated numbers. A network range such as 192.0.2.0/24 runs from 192.0.2.0 through 192.0.2.255. The prefix /24 fixes the first 24 bits, the zero-or-one binary digits. Ranges include their first and last addresses for this comparison. That does not mean each can be assigned to a device.

2. Compare the fictional lists

Left.txt contains:

192.0.2.0/24
198.51.100.0/24

Right.txt contains:

192.0.2.128/25
203.0.113.0/24

Open a command window in the extracted folder and run:

python3 CheckRangeOverlap.py Left.txt Right.txt

Use python or py instead if that is your Python 3 command. Expected output:

Left line 1 (192.0.2.0/24) / right line 1 (192.0.2.128/25): 192.0.2.128 to 192.0.2.255; 128 addresses
Compared: 2 left ranges; 2 right ranges; 1 overlapping pairs
Unique overlapping addresses: 128

The first right-hand range is inside the first left-hand range. Exit code 1, the small result number returned to the command window, means the comparison finished and found overlap.

3. Try a separate list, then run the tests

python3 CheckRangeOverlap.py Left.txt Disjoint.txt
python3 TestRangeOverlap.py

Disjoint.txt contains 203.0.113.0/25. Its comparison completes with zero overlapping pairs and exit 0. The test runner should end with OK. It checks fictional temporary files, preserves input bytes and compares 400 small random range pairs with address sets. It also checks 300 whole-list unique-address totals against independent address sets. Fixed random seeds make the cases repeatable. A failed test returns nonzero; investigate rather than treating it as a completed check.

4. Use your own saved copies carefully

One strict IPv4 network and prefix per line, with /0 through /32. A single address still needs /32. 192.0.2.1/24 stops because it is not the start of that range. The checker never silently widens it. Dotted masks, comments, blank lines and Internet Protocol version 6 (IPv6) are not accepted.

Both lists are fully checked before any findings print. A malformed list stops with exit 2, and no completed comparison. Empty lists also stop. UTF-8 text with an optional initial byte-order marker is accepted; surrounding spaces are removed. A final newline is not an extra line.

Each file may be up to 1 MiB (mebibyte), exactly 1,048,576 bytes, and 250 lines. Only the first 500 overlapping pairs have details, in left-list then right-list order. The summary counts all pairs and states how many details were omitted. A capped report still exits 1.

5. Read the scope before changing anything

This compares each left line with each right line. It does not compare lines within one list. Duplicate lines count separately. If you supply the same file twice, every range matches itself and the two directions of a pair count separately. Do not add address counts across pairs: the same address can appear in several findings. The new Unique overlapping addresses total counts each address only once across all shared ranges, including pairs omitted by the detail limit. It merges range endpoints without listing the addresses. It is not a count of devices or usable hosts.

Overlap can be intentional. No overlap does not prove there are no network conflicts, that space is unused, or that a change is approved. No device, route, firewall traffic rule, reachability, ownership or permission is checked. The program makes no network request and changes no input file. Keep reports private because they reveal address ranges. Use copies that will not change while read. Never redirect output over an input file.

The complete program

Version 1.1.0 adds the unique overlapping-address total; exit codes and pair details are unchanged. The download includes this exact code. Printed lines may wrap: copy from this page or the original .py file, not a printout.

"""Compare two saved IPv4 range lists locally. Python 3.10+, no packages."""
import argparse
from dataclasses import dataclass
import ipaddress
from pathlib import Path
import re
import sys

MAX_BYTES = 1048576
MAX_LINES = 250
MAX_FINDINGS = 500
PREFIX = re.compile(r"(?:0|[1-9][0-9]?)\Z")


@dataclass(frozen=True)
class Entry:
    line: int
    network: ipaddress.IPv4Network


def read_list(path):
    with Path(path).open("rb") as source:
        raw = source.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError("file exceeds 1 MiB (1,048,576 bytes)")
    lines = raw.decode("utf-8-sig").splitlines()
    if len(lines) > MAX_LINES:
        raise ValueError("file exceeds 250 lines")
    if not lines:
        raise ValueError("list is empty")
    entries = []
    for number, line in enumerate(lines, 1):
        text = line.strip()
        parts = text.split("/")
        if len(parts) != 2 or not PREFIX.fullmatch(parts[1]):
            raise ValueError(f"line {number}: use an IPv4 network and /0 through /32")
        try:
            network = ipaddress.IPv4Network(text, strict=True)
        except ValueError:
            # Do not echo untrusted lines or terminal escape sequences.
            raise ValueError(f"line {number}: invalid IPv4 network or host bits set") from None
        entries.append(Entry(number, network))
    return entries


def intersections(left, right):
    """Stream pair findings without listing individual addresses."""
    for a in left:
        for b in right:
            if a.network.overlaps(b.network):
                start = max(int(a.network.network_address), int(b.network.network_address))
                end = min(int(a.network.broadcast_address), int(b.network.broadcast_address))
                yield a, b, ipaddress.IPv4Address(start), ipaddress.IPv4Address(end), end - start + 1


def unique_address_count(intervals):
    """Count the union of inclusive integer intervals, not their pair sum."""
    if not intervals:
        return 0
    ordered = sorted(intervals)
    start, end = ordered[0]
    total = 0
    for next_start, next_end in ordered[1:]:
        if next_start <= end + 1:
            end = max(end, next_end)
        else:
            total += end - start + 1
            start, end = next_start, next_end
    return total + end - start + 1


def main(argv=None):
    parser = argparse.ArgumentParser(description="Compare two local IPv4 network lists for overlaps. No network traffic.")
    parser.add_argument("left", help="UTF-8 file: one strict IPv4 network/prefix per line")
    parser.add_argument("right", help="second UTF-8 file; no blank lines or comments")
    args = parser.parse_args(argv)
    lists = []
    # Validate both completely before writing any findings to stdout.
    for side, path in [("left", args.left), ("right", args.right)]:
        try:
            lists.append(read_list(path))
        except (OSError, UnicodeError):
            print(f"Check stopped: {side} list could not be read as UTF-8.", file=sys.stderr)
            return 2
        except ValueError as error:
            print(f"Check stopped: {side} list: {error}", file=sys.stderr)
            return 2
    count = 0
    shared_intervals = []
    for a, b, start, end, size in intersections(*lists):
        count += 1
        shared_intervals.append((int(start), int(end)))
        if count <= MAX_FINDINGS:
            print(f"Left line {a.line} ({a.network}) / right line {b.line} ({b.network}): {start} to {end}; {size} addresses")
    if count > MAX_FINDINGS:
        print(f"Detail limit: first {MAX_FINDINGS} pairs shown; {count - MAX_FINDINGS} pairs omitted.")
    print(f"Compared: {len(lists[0])} left ranges; {len(lists[1])} right ranges; {count} overlapping pairs")
    print(f"Unique overlapping addresses: {unique_address_count(shared_intervals)}")
    return 1 if count else 0


if __name__ == "__main__":
    raise SystemExit(main())

Sources

Tested on Python 3.10.12. MIT licence, copyright 2026 William Baptist.