PREP WITH PROOF
Menu
NETWORKING & INFRASTRUCTURE / PRACTICAL GUIDE

CIDR Overlap and Subnetting: Calculate Ranges with Python

Calculate CIDR ranges, detect overlapping networks and split subnets with Python ipaddress. Includes host-bit checks and an independently verified IPv4/IPv6 lab.

THE QUICK ANSWER

Two same-family networks overlap when their inclusive address ranges share at least one address. Compare their numeric boundaries, not their spelling or only their usable-host lists. A CIDR prefix also defines an aligned block: host bits must be zero in a strict network definition. Python ipaddress can check these properties, split a parent into smaller networks and distinguish a host interface from its containing network.

Review an address interval before approving an allocation

A proposed subnet can look different from an existing one while occupying the same addresses. Different prefix lengths, host bits in the submitted address, or compressed IPv6 spelling can hide the relationship. A dependable review starts with the numeric range each network represents, then applies the allocation policy to those ranges.

For example, 192.0.2.0/24 covers addresses from 192.0.2.0 through 192.0.2.255. A proposed 192.0.2.64/26 lies inside that range even though the textual prefixes differ. Comparing the two strings, or searching only for an exact CIDR match in an inventory, would fail to detect the containment.

This guide uses Python 3.12.14 to demonstrate the arithmetic without sending traffic or changing routes. The complete lab passed 2428 checks, including 400 generated IPv4/IPv6 pairs checked against independent integer intervals. The result verifies address calculations; it does not establish that a route, firewall rule, VPN or cloud connection will work.

A prefix defines both a size and an alignment

IPv4 has 32 address bits. A /p prefix fixes the first p bits and leaves 32 minus p bits to vary, giving 2 raised to that remaining-bit count addresses. A /26 therefore describes 64 addresses. Its starting address must also be aligned to a 64-address boundary; choosing any arbitrary run of 64 addresses does not create a /26.

Inside 192.0.2.0/24, the /26 boundaries occur at last-octet values 0, 64, 128 and 192. The interval beginning at .64 ends at .127. The next interval starts at .128, so those two intervals touch at a boundary between addresses but share no address. Avoid treating the upper boundary as an extra usable endpoint.

CIDR arithmetic describes the complete address set. Keep that count separate from a usable-host convention or a platform’s assignable capacity. An allocation review needs both the exact range and the deployment rules, but one cannot be inferred simply by subtracting a fixed number from every prefix size.

IPv4 prefixTotal addressesExample interval
192.0.2.0/24256192.0.2.0–192.0.2.255
192.0.2.64/2664192.0.2.64–192.0.2.127
192.0.2.0/304192.0.2.0–192.0.2.3
192.0.2.0/312192.0.2.0–192.0.2.1
192.0.2.1/321192.0.2.1 only

Source: RFC 4632: CIDR address assignment and aggregation ↗

Distinguish a network from an interface address

The string 192.0.2.70/26 combines a host address with a prefix. It is useful as an interface description, but .70 is not the aligned starting address of that network. ip_network with strict=True rejects the host bits, which is often useful when reviewing an allocation that should name the network itself.

With strict=False, Python normalizes that input to 192.0.2.64/26. That is an explicit interpretation, not proof that the submitter intended the resulting allocation. An approval workflow should retain the original input and show the normalized range before accepting it. Otherwise, a typo can be converted into a plausible but unintended network.

Use ip_interface when the host address is meant to be retained. Its ip property preserves 192.0.2.70, while its network property identifies 192.0.2.64/26. The lab checks both. The small read_network helper also requires an explicit slash and mask/prefix, avoiding an accidental assumption that a bare host address means a requested subnet.

Source: Python 3.12 ipaddress: networks, interfaces, overlap and subnet operations ↗

Overlap, equality and containment answer different questions

For inclusive intervals [startA, endA] and [startB, endB], overlap exists when the larger start is no greater than the smaller end. Containment is stricter: the inner range must start no earlier and end no later than the outer range. These integer comparisons form the independent oracle in the lab.

The same network overlaps itself. A smaller subnet inside a parent also overlaps that parent, while the reverse containment question has a different answer. If the rule is “no shared address between allocations,” both equality and containment need rejection. If the rule intentionally permits nested delegations, record that relationship rather than treating every overlap as an operational error.

For canonical CIDR blocks in the same address family, an overlap means one block contains the other, including equality. Arbitrary address intervals can partially overlap without containment, so do not transfer every interval intuition to aligned CIDR blocks. Use the range test for clarity, then report the more specific relationship.

Do not compare one IPv4 allocation with one IPv6 allocation as though their integer values belonged to the same address space. The example overlap helper explicitly rejects mixed families. It also compares complete network ranges, including endpoints, instead of comparing hosts() results. Host-iteration conventions should not redefine whether allocated address space intersects.

Source: Python 3.12 ipaddress: networks, interfaces, overlap and subnet operations ↗

Split a parent, then verify the partition

Increasing a prefix length creates smaller blocks. Splitting a /24 into /26 networks adds two prefix bits and creates four equal subnets. Each contains 64 addresses, their ranges are disjoint, and together they cover the original 256 addresses. The lab checks the exact four network strings and independently checks generated child boundaries.

A requested prefix equal to the parent’s prefix returns that same network as a one-element result in the tested library. Asking subnets() for /23 children of a /24 is the wrong direction and raises an error: /23 would describe a larger network. Decide whether the operation is subdivision or aggregation before choosing an API call.

Aggregation also needs alignment. The two sibling /25 blocks in the example collapse exactly to their /24 parent. By contrast, adjacent 192.0.2.64/26 and 192.0.2.128/26 do not collapse to one exact CIDR block. Combining them into a broader single prefix would include additional addresses. An adjacent pair is not automatically a valid exact aggregation.

Source: Python 3.12 ipaddress: networks, interfaces, overlap and subnet operations ↗

Do not make “total minus two” a universal capacity rule

For the IPv4 /30 example, Python hosts() yields two host addresses, excluding the conventional network and broadcast endpoints. The tested /31 iterator yields both addresses, and /32 yields its single address. These explicit cases are why a blanket “subtract two” implementation produces wrong results at small prefixes.

An IPv6 /64 contains 2 raised to 64 addresses. Read num_addresses or use arithmetic instead of materializing every address in a list. The lab uses integer endpoints and only small bounded subnet lists, so it can check large prefixes without enumerating their hosts. Use the same approach when building an inventory review utility.

IPv6 has no broadcast addresses in the protocol. Python still exposes a broadcast_address attribute on an IPv6 network object; this lab uses that attribute as the numeric upper endpoint, not as a claim that IPv6 sends broadcast traffic. Keep library attribute names separate from packet-delivery semantics.

Finally, an address count is not a deployment authorization or a guaranteed number of assignable machines. Confirm the platform’s reserved addresses, permitted subnet sizes and routing constraints separately. A correct interval calculation cannot tell you whether a provider accepts the requested prefix or whether the required route is installed.

Source: RFC 4291: IPv6 addressing architecture ↗

Run the complete arithmetic lab

Save this as cidr_lab.py and run it with Python 3.12. The code uses only the standard library. Its fixed examples cover strict input, interface preservation, overlap, containment, adjacent ranges, subdivision, host-count exceptions, IPv6 and exact aggregation. No credentials or network access are needed.

The generated cases use a fixed random seed and explicit IPv4Network or IPv6Network constructors. That explicit family selection matters for an integer start of zero, which should not silently choose the wrong address family. Half the generated pairs deliberately contain a nested subnet; the others use independently selected blocks.

The expected boundaries come from integer division and powers of two. Overlap and containment expectations use inclusive interval comparisons, while subdivision expectations use a bounded range step. They do not call the ipaddress methods being checked. Each parent produces at most eight children, and no large host iterator is converted to a list.

import ipaddress as ip
import random

checks = 0

def check(condition):
    global checks
    if not condition:
        raise AssertionError('Unexpected CIDR result')
    checks += 1

def rejects(call, error=ValueError):
    global checks
    try:
        call()
    except error:
        checks += 1
    else:
        raise AssertionError('Expected rejection')

def read_network(text):
    if not isinstance(text, str) or '/' not in text:
        raise ValueError('Supply an address and an explicit mask/prefix')
    return ip.ip_network(text, strict=True)

def overlap(left, right):
    a, b = read_network(left), read_network(right)
    if a.version != b.version:
        raise ValueError('Compare networks from the same IP family')
    return a.overlaps(b)

# Fixed examples: no sockets, routes or cloud resources are changed.
parent = read_network('192.0.2.0/24')
child = read_network('192.0.2.64/26')
check(str(parent.network_address) == '192.0.2.0')
check(str(parent.broadcast_address) == '192.0.2.255')
check(parent.num_addresses == 256 and child.num_addresses == 64)
check(overlap(str(parent), str(child)))
check(child.subnet_of(parent) and not parent.subnet_of(child))
check(not overlap('192.0.2.0/25', '192.0.2.128/25'))
check(overlap('192.0.2.0/24', '192.0.2.0/24'))
check(ip.ip_address('192.0.2.127') in child)
check(ip.ip_address('192.0.2.128') not in child)
rejects(lambda: read_network('192.0.2.70/26'))
check(str(ip.ip_network('192.0.2.70/26', strict=False)) == '192.0.2.64/26')
interface = ip.ip_interface('192.0.2.70/26')
check(str(interface.ip) == '192.0.2.70' and interface.network == child)
for bad in ['192.0.2.0', '192.0.2.0/33', '2001:db8::/129', '999.0.0.0/24']:
    rejects(lambda bad=bad: read_network(bad))
rejects(lambda: overlap('192.0.2.0/24', '2001:db8::/32'))
check([str(n) for n in parent.subnets(new_prefix=26)] == [
    '192.0.2.0/26', '192.0.2.64/26', '192.0.2.128/26', '192.0.2.192/26'])
check(list(parent.subnets(new_prefix=24)) == [parent])
rejects(lambda: list(parent.subnets(new_prefix=23)))
check(len(list(read_network('192.0.2.0/30').hosts())) == 2)
check(len(list(read_network('192.0.2.0/31').hosts())) == 2)
check(len(list(read_network('192.0.2.1/32').hosts())) == 1)
v6 = read_network('2001:db8::/64')
check(v6.num_addresses == 2**64)  # Do not materialize all hosts.
check(overlap('2001:db8::/32', '2001:db8:1::/48'))
check(not overlap('2001:db8:1::/48', '2001:db8:2::/48'))
check([str(n) for n in ip.collapse_addresses([
    read_network('192.0.2.0/25'), read_network('192.0.2.128/25')])] == ['192.0.2.0/24'])
check(len(list(ip.collapse_addresses([
    read_network('192.0.2.64/26'), read_network('192.0.2.128/26')]))) == 2)

# Independent oracle: inclusive integer intervals, not host enumeration.
rng = random.Random(66)
for width, cls in [(32, ip.IPv4Network), (128, ip.IPv6Network)]:
    for i in range(200):
        prefix = rng.randrange(width + 1)
        size = 2 ** (width - prefix)
        start = (rng.getrandbits(width) // size) * size
        end = start + size - 1
        other_prefix = rng.randrange(prefix, width + 1) if i % 2 == 0 else rng.randrange(width + 1)
        other_size = 2 ** (width - other_prefix)
        other_start = (start + rng.randrange(size // other_size) * other_size
                       if i % 2 == 0 else (rng.getrandbits(width) // other_size) * other_size)
        other_end = other_start + other_size - 1
        a, b = cls((start, prefix)), cls((other_start, other_prefix))
        expected_overlap = max(start, other_start) <= min(end, other_end)
        check((int(a.network_address), int(a.broadcast_address), a.num_addresses) == (start, end, size))
        check((int(b.network_address), int(b.broadcast_address), b.num_addresses) == (other_start, other_end, other_size))
        check(a.overlaps(b) == b.overlaps(a) == expected_overlap)
        check(a.subnet_of(b) == (other_start <= start and end <= other_end))
        check(b.subnet_of(a) == (start <= other_start and other_end <= end))
        child_prefix = min(width, prefix + 3)
        child_size = 2 ** (width - child_prefix)
        actual = [(int(n.network_address), int(n.broadcast_address))
                  for n in a.subnets(new_prefix=child_prefix)]
        expected = [(lo, lo + child_size - 1)
                    for lo in range(start, end + 1, child_size)]
        check(actual == expected)
print(f'PASS: {checks} checks; 400 generated IPv4/IPv6 pairs; no network traffic')

Turn the calculation into a useful review result

A review record should show the submitted value, canonical network, address family, prefix length, total addresses, inclusive lower and upper endpoints, and any conflicting allocation identifier. Report whether the match is equality, containment or no overlap. A bare true/false result leaves too much interpretation for the next operator.

When a request fails strict parsing, ask the workflow to resolve whether it is an interface assignment or a network allocation. When it overlaps, inspect the intended hierarchy and address plan before selecting a different range. When arithmetic passes but connectivity fails, investigate routes, name resolution and traffic controls as separate layers.

The practical goal is a repeatable allocation decision with visible boundaries. Preserve the independent checks as regression evidence and apply the same parsing policy to inventory entries and proposed networks. That makes a later change in prefix length or notation easier to review without mistaking a different string for a different address space.

KEEP THESE THREE THINGS

Your next steps

  1. Normalize the meaning of the input first: a network allocation, a host address with a mask, or an intentionally normalized range. Do not silently erase host bits during approval.
  2. Check overlap using complete inclusive ranges and compare only one IP family at a time. Equality and containment are conflicts when the allocation rule forbids any shared address.
  3. Separate address arithmetic from usable capacity and routing behavior. Keep an independent range check and verify the platform policy before deploying an allocation.

Sources & official resources

Linked resources checked on 2026-10-31. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →