networking · beginner · ~15 min

Does an IPv4 address match a CIDR block?

CIDR matching via bitmask — the firewall primitive.

Challenge

Implement int cidr_match(unsigned ip, unsigned net, int prefix_bits).

All addresses are passed as host-order unsigned (e.g. 192.168.1.5 → 0xC0A80105). prefix_bits is in [0, 32]. Returns 1 if ip falls within the net/prefix block, else 0.

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, net, prefix.

Output format

0/1.

Constraints

No allocations; pure arithmetic.

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.