networking · intermediate · ~25 min

Does an IPv4 CIDR block contain an address?

Bitmask construction; integer overflow guards in shifts.

Challenge

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.

Why this matters

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.

Input format

network, ip as uint32_t. prefix_bits in [0, 32].

Output format

0 or 1.

Constraints

No loops needed; closed-form bit math.

Starter code

#include <stdint.h>
int cidr_contains(uint32_t network, int prefix_bits, uint32_t ip) { /* TODO */ return 0; }

Common mistakes

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

Edge cases to handle

prefix 0 → mask is 0, every IP matches. prefix 32 → exact match.

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.