networking · beginner · ~15 min

Does an IPv4 address match a CIDR block?

CIDR matching via bitmask — the firewall primitive.

Challenge

Decide whether an IPv4 address falls inside a CIDR block — the bit math behind every firewall allow-list.

Task

Implement int cidr_match(unsigned ip, unsigned net, int prefix_bits) that returns 1 if ip is inside the net/prefix_bits block, else 0.

Input

  • ip, net: IPv4 addresses as host-order unsigned (e.g. 192.168.1.5 → 0xC0A80105).
  • prefix_bits: the CIDR prefix length, valid range [0, 32].

Output

Return 1 if the top prefix_bits of ip and net match, else 0. A prefix_bits outside [0, 32] returns 0.

Example

cidr_match(0xC0A80105, 0xC0A80100, 24)  ->  1   (192.168.1.5 in 192.168.1.0/24)
cidr_match(0xC0A80205, 0xC0A80100, 24)  ->  0   (192.168.2.5 not in /24)
cidr_match(0x08080808, 0x00000000, 0)   ->  1   (/0 matches everything)
cidr_match(0x08080808, 0x08080808, 32)  ->  1   (/32 exact match)
cidr_match(0x00000000, 0x00000000, -1)  ->  0   (invalid prefix)
cidr_match(0x00000000, 0x00000000, 33)  ->  0   (invalid prefix)

Edge cases

  • prefix_bits == 0: always matches (return 1).
  • prefix_bits == 32: exact match required.
  • prefix_bits < 0 or > 32: return 0.

Rules

  • Pure arithmetic; no allocations.

Why this matters

Every firewall, every WAF, every allow-list gateway runs this check millions of times per second. The bit math is short but error-prone — get it right once and reuse.

Input format

ip and net as host-order unsigned IPv4 addresses; prefix_bits, the CIDR length.

Output format

1 if ip is inside net/prefix_bits, else 0; an out-of-range prefix returns 0.

Constraints

prefix_bits valid in [0,32]; pure arithmetic, no allocations.

Starter code

int cidr_match(unsigned ip, unsigned net, int prefix_bits) { /* TODO */ (void)ip; (void)net; (void)prefix_bits; return 0; }

Common mistakes

Off-by-one with prefix == 0 (matches everything) or prefix == 32 (exact match).

Edge cases to handle

prefix == 0 → always 1. prefix == 32 → exact match. Negative prefix → reject.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.