Reject Host Bits in Python IPv4 CIDR Configuration

A deployment configuration expects an IPv4 network such as 192.0.2.0/24. Someone enters 192.0.2.7/24, intending a single machine. Silently converting that value into 192.0.2.0/24 changes the scope of the configuration. A parser should report the mismatch before the value reaches the component that applies it.

These examples use Python 3.10 or later and the standard library. The configuration format deliberately requires an IPv4 address followed by an explicit decimal prefix length. It accepts network definitions, including single-address /32 networks.

See What Disabling Strict Parsing Changes

Run this standalone example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from ipaddress import IPv4Network

text = "192.0.2.7/24"
print(IPv4Network(text, strict=False))
try:
    IPv4Network(text, strict=True)
except ValueError:
    print("Rejected: host bits are set")
# 192.0.2.0/24
# Rejected: host bits are set

A /24 prefix leaves eight bits for the host portion. The final octet 7 sets some of those bits. With strict=False, the constructor clears them; with strict=True, it rejects this input. The IPv4Network reference documents both behaviors.

Masking is useful when a tool explicitly asks which network contains an address. Here the field asks for the network itself, so changing the supplied address would hide a configuration mistake.

Require the Configuration’s Exact Input Shape

Save this as cidr_config.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import re
from ipaddress import IPv4Network


def parse_ipv4_cidr(text):
    if not isinstance(text, str):
        raise TypeError("CIDR must be a string")
    if re.fullmatch(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}/(?:0|[1-9][0-9]?)", text) is None:
        raise ValueError("expected IPv4 address/decimal prefix length")
    return IPv4Network(text, strict=True)

The regular expression checks the configuration’s spelling rules: four decimal components, a slash, and a decimal prefix without leading zeros. It rejects whitespace, missing prefixes, dotted netmasks, IPv6, and signs. It does not prove that octets or prefix lengths are in range; the constructor performs those checks and checks network alignment.

There are two distinct validation layers because strict=True refers to host bits, rather than to this particular text grammar. The library accepts additional input forms, including an address without an explicit prefix and a dotted netmask. This helper intentionally offers a smaller format. It leaves the constructor’s ValueError available to a caller that wants to report the invalid configuration field.

Keep Address Membership Separate from Text Matching

Save this demonstration beside the helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from ipaddress import IPv4Address
from cidr_config import parse_ipv4_cidr

network = parse_ipv4_cidr("192.0.2.0/24")
print(str(network))
print(network.num_addresses)
for text in ["192.0.2.0", "192.0.2.7", "192.0.2.255", "192.0.3.0"]:
    print(text, IPv4Address(text) in network)
# 192.0.2.0/24
# 256
# 192.0.2.0 True
# 192.0.2.7 True
# 192.0.2.255 True
# 192.0.3.0 False

Use parsed address membership when checking whether an address belongs to the configured range. A string prefix comparison does not express CIDR boundaries. The ipaddress introduction explains network containment with address objects.

Membership includes the network and broadcast addresses. This example answers a range question; it does not select assignable interface addresses. It also avoids expanding the network into a list, so the same operation remains practical for a large range.

Test Alignment and Prefix Boundaries

Save this as test_cidr_config.py beside the helper and run python test_cidr_config.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from cidr_config import parse_ipv4_cidr

for text, count in [
    ("0.0.0.0/0", 2 ** 32),
    ("192.0.2.0/24", 256),
    ("192.0.2.128/25", 128),
    ("192.0.2.6/31", 2),
    ("192.0.2.7/32", 1),
]:
    network = parse_ipv4_cidr(text)
    assert str(network) == text
    assert network.num_addresses == count

for text in [
    "192.0.2.7/24", "192.0.2.127/25", "192.0.2.7/31",
    "192.0.2.1/0", "192.0.2.0/33", "256.0.0.0/24",
    "192.0.02.0/24", "192.0.2.0", "192.0.2.0/255.255.255.0",
    "192.0.2.0/024", "192.0.2.0/+24", "192.0.2.0/24\n",
    " 192.0.2.0/24", "2001:db8::/32", "",
]:
    try:
        parse_ipv4_cidr(text)
    except ValueError:
        pass
    else:
        raise AssertionError(f"invalid CIDR accepted: {text!r}")

for value in [None, 0, True, b"192.0.2.0/24"]:
    try:
        parse_ipv4_cidr(value)
    except TypeError:
        pass
    else:
        raise AssertionError(f"non-string CIDR accepted: {value!r}")

print("Strict CIDR checks passed.")

The /25 pair catches implementations that check only whether the final octet is zero: 192.0.2.128/25 is aligned and valid. The /31 pair checks the last host bit. /0 and /32 exercise the extremes without enumerating their addresses. The newline case verifies that the entire configuration string must match.

Apply Deployment Policy After Parsing

Parsing establishes a valid, aligned IPv4 network in the required text format. A deployment can still impose its own restrictions. For example, a field might prohibit /0, require a particular parent range, or disallow overlapping entries. Apply those rules to the returned network object before storing or using the configuration.

If another field represents an interface address with its prefix, a value such as 192.0.2.7/24 can be appropriate there. Python provides IPv4Interface for that representation. Choose the object according to the field’s meaning rather than enabling silent masking to make a failing input pass.

Store str(network) when the configuration needs a stable network spelling. Keep the original input separately if diagnostics require it. For this field, explicit prefix syntax and strict network alignment make a mistaken host address visible at the point of entry.