Skip to content

Lesson 5 of 14 · 18m

ipaddress: CIDR math without the string bugs

Membership, overlap, and aggregation on real net objects instead of `startswith` guesses.

The blocklist pipeline needs a membership test: is 203.0.113.7 inside 203.0.113.0/24? The string answer — ip.startswith("203.0.113.") — works on this example and fails on the next: 203.0.113.0/25 still starts with 203.0.113. but only covers half the block, and 10.0.0.1.startswith("10.") is True while 10. as a prefix means /8, not "any address beginning with 10". IP addresses are integers wearing dotted text as a costume, and every real question about them — containment, overlap, aggregation — is integer math. ipaddress does the math correctly; strings do not.

The operations you'll actually use

from ipaddress import ip_address, ip_network, collapse_addresses

ip = ip_address("203.0.113.7")
net = ip_network("203.0.113.0/24")

ip in net                    # True — the membership test you wanted
ip.is_private                # True — TEST-NET-3 is on the IANA special-purpose list
net.num_addresses            # 256
net.network_address          # IPv4Address('203.0.113.0')
net.broadcast_address        # IPv4Address('203.0.113.255')
list(net.hosts())[:2]        # [IPv4Address('203.0.113.1'), ...] — usable hosts only

ip in net is the single most valuable line — it replaces the whole class of prefix-string bugs by doing bit math on the integer instead of matching octets: 10.128.0.1 starts with 10. yet falls outside 10.0.0.0/9, which no string check sees. Feed it both directions: is this source IP inside our 10.0.0.0/8 (internal traffic, skip alerting), or inside the threat feed's 45.148.10.0/24 block (escalate).

Untrusted input and host bits

Two exceptions cover nearly all bad input. ip_address raises ValueError on garbage — ip_address("not.an.ip"), ip_address("300.1.2.3"). And ip_network defaults to strict=True, meaning it rejects networks with host bits set:

ip_network("203.0.113.7/24")              # ValueError: 203.0.113.7/24 has host bits set
ip_network("203.0.113.7/24", strict=False)  # OK → 203.0.113.0/24

That's a deliberate design: 203.0.113.7/24 is ambiguous — the author might mean the single host's block or the whole /24. Real feeds hand you both shapes, so parse with strict=False when the input means "the network containing this address" (firewall rules, AWS ip-ranges.json, fail2ban ignoreip entries), and keep strict=True where the distinction matters (defining a block you own).

Aggregation, overlap, and the family trap

collapse_addresses([ip_network("203.0.113.0/25"), ip_network("203.0.113.128/25")])
# → [IPv4Network('203.0.113.0/24')] — dedup and merge adjacent blocks

collapse_addresses is the whole answer to "merge my blocklist" — it handles the bit-level merging you would otherwise get wrong by hand. net_a.overlaps(net_b) answers "do these rules conflict," and net.subnets(prefixlen_diff=1) splits a block in half for sharding work.

Feeds that hand you start–end ranges instead of CIDRs need one more conversion: summarize_address_range(ip_address("203.0.113.5"), ip_address("203.0.113.20")) yields the minimal covering set — /32, /31, /29, /30, /32 on that example — which is the only correct answer to "what CIDRs is this range," because a human-chosen range almost never lands on a single boundary.

The family trap: IPv4 and IPv6 objects refuse to compare — ip_address("::1") in ip_network("10.0.0.0/8") raises TypeError, not False. If your input mixes families (any dual-stack log does), wrap the containment test:

def in_scope(ip_str, nets):
    try:
        ip = ip_address(ip_str)
    except ValueError:
        return False                       # hostname, corrupt field — not our business
    return any(ip in n for n in nets if ip.version == n.version)

Try this

Load AWS's published ip-ranges.json (a public feed of {"ip_prefix": "x.y.z.0/n"} entries) and write is_aws(ip) — parse once into a list of ip_network, then test membership. Point it at the source IPs from the auth.log parser and count how much of your "attack traffic" is a scanner running on EC2. Then collapse your own internal ranges with collapse_addresses and verify no overlap with the RFC1918 block you meant.

Field notes

  • is_private is not "internal to you." It's the IANA special-purpose registry, wider than RFC1918 — link-local, loopback, the TEST-NET documentation blocks, 198.18.0.0/15 benchmarking, reserved 240.0.0.0/4 all read True — while shared address space 100.64.0.0/10 (carrier-grade NAT) reads False on current CPython: deliberately neither private nor global, so CGNAT subscriber traffic slips past an is_private screen. is_global answers the other direction — your 172.16.0.0/12 and the coffee shop's both read private, never yours alone.
  • net.hosts() excludes network and broadcast for /31 and longer prefixes it includes them (RFC 3021 semantics). Don't iterate it into an allowlist without knowing which behavior you got.
  • The bug that ships: .startswith prefix matching and string-range comparisons — they pass unit tests on hand-picked examples and fail on the first /25 or IPv6 address.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.