networking · intermediate · ~15 min
Apply the prefix mask to compare two addresses.
Decide whether an IPv4 address sits inside a CIDR network — the cornerstone of routing-table and firewall lookups.
Implement int cidr_contains(uint32_t net, int prefix, uint32_t ip) that returns 1 if ip is inside net/prefix, else 0.
net, ip: IPv4 addresses as uint32_t in host byte order.prefix: the prefix length, 0..32.Return 1 if the top prefix bits of ip and net match, else 0.
cidr_contains(0xC0A80100, 24, 0xC0A8017F) -> 1 (192.168.1.127 in 192.168.1.0/24)
cidr_contains(0xC0A80100, 24, 0xC0A80200) -> 0 (outside)
cidr_contains(0x00000000, 0, 0xDEADBEEF) -> 1 (/0 matches everything)
prefix == 0: the mask is 0, so every IP matches.prefix == 0 to avoid the shift-by-32 undefined behaviour.net and ip as host-order uint32_t IPv4 addresses; prefix: 0..32.
1 if ip is inside net/prefix, else 0.
Mask both addresses by the prefix and compare; special-case prefix==0 to avoid shift-by-32 UB.
#include <stdint.h>
int cidr_contains(uint32_t net, int prefix, uint32_t ip) { /* TODO */ return 0; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.