networking · beginner · ~15 min
CIDR matching via bitmask — the firewall primitive.
Decide whether an IPv4 address falls inside a CIDR block — the bit math behind every firewall allow-list.
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.
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].Return 1 if the top prefix_bits of ip and net match, else 0. A prefix_bits outside [0, 32] returns 0.
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)
prefix_bits == 0: always matches (return 1).prefix_bits == 32: exact match required.prefix_bits < 0 or > 32: return 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 and net as host-order unsigned IPv4 addresses; prefix_bits, the CIDR length.
1 if ip is inside net/prefix_bits, else 0; an out-of-range prefix returns 0.
prefix_bits valid in [0,32]; pure arithmetic, no allocations.
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.