networking · beginner · ~15 min
CIDR matching via bitmask — the firewall primitive.
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.
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.
ip, net, prefix.
0/1.
No allocations; pure arithmetic.
int cidr_match(unsigned ip, unsigned net, int prefix_bits) { /* TODO */ (void)ip; (void)net; (void)prefix_bits; return 0; }
Off-by-one with prefix == 0 (matches everything) or prefix == 32 (exact match).
prefix == 0 → always 1. prefix == 32 → exact match. Negative prefix → reject.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.