networking · intermediate · ~15 min
Bitmask arithmetic on IPv4 addresses.
Compute the network base address of an IPv4 address by zeroing its host bits.
Implement uint32_t network_address(uint32_t ip, int prefix_len) that returns ip with the low (32 - prefix_len) host bits cleared.
ip: an IPv4 address as a uint32_t in host byte order.prefix_len: the network prefix length, 0..32.The network base address: the top prefix_len bits of ip, with the rest zeroed.
network_address(0xC0A80105, 24) -> 0xC0A80100 (192.168.1.5/24 -> 192.168.1.0)
network_address(0x0A0B0C0D, 16) -> 0x0A0B0000
network_address(0xDEADBEEF, 0) -> 0x00000000 (/0 zeroes everything)
network_address(0x01020304, 32) -> 0x01020304 (/32 keeps everything)
prefix_len == 0: the mask is 0, so the result is 0.prefix_len == 32: nothing is masked off; the address is returned unchanged.prefix_len == 0.ip: host-order uint32_t IPv4 address; prefix_len: 0..32.
ip with the low (32 - prefix_len) bits cleared.
Special-case prefix_len==0 to avoid the shift-by-32 UB.
#include <stdint.h>
uint32_t network_address(uint32_t ip, int prefix_len) { /* TODO */ return 0; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.