networking · intermediate · ~15 min

Does CIDR contain IP?

Apply the prefix mask to compare two addresses.

Challenge

Decide whether an IPv4 address sits inside a CIDR network — the cornerstone of routing-table and firewall lookups.

Task

Implement int cidr_contains(uint32_t net, int prefix, uint32_t ip) that returns 1 if ip is inside net/prefix, else 0.

Input

  • net, ip: IPv4 addresses as uint32_t in host byte order.
  • prefix: the prefix length, 0..32.

Output

Return 1 if the top prefix bits of ip and net match, else 0.

Example

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)

Edge cases

  • prefix == 0: the mask is 0, so every IP matches.
  • Special-case prefix == 0 to avoid the shift-by-32 undefined behaviour.

Input format

net and ip as host-order uint32_t IPv4 addresses; prefix: 0..32.

Output format

1 if ip is inside net/prefix, else 0.

Constraints

Mask both addresses by the prefix and compare; special-case prefix==0 to avoid shift-by-32 UB.

Starter code

#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.