networking · intermediate · ~25 min
Bitmask construction; integer overflow guards in shifts.
Implement int cidr_contains(uint32_t network, int prefix_bits, uint32_t ip). Returns 1 if ip falls inside the block specified by network and prefix length prefix_bits (0..32), else 0. All values are in host byte order.
Every firewall, every cloud security group, every IP allowlist relies on CIDR-membership checks. This is the inner loop of iptables, nftables, and your AWS VPC ACL evaluator.
network, ip as uint32_t. prefix_bits in [0, 32].
0 or 1.
No loops needed; closed-form bit math.
#include <stdint.h>
int cidr_contains(uint32_t network, int prefix_bits, uint32_t ip) { /* TODO */ return 0; }
Computing the mask with (1<<prefix)-1 then shifting — wrong by an off-by-one; shifting a uint32_t by 32 (undefined behaviour in C); not handling prefix==0 (matches everything).
prefix 0 → mask is 0, every IP matches. prefix 32 → exact match.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.