networking · intermediate · ~15 min

Compute network address from IP + prefix

Bitmask arithmetic on IPv4 addresses.

Challenge

Compute the network base address of an IPv4 address by zeroing its host bits.

Task

Implement uint32_t network_address(uint32_t ip, int prefix_len) that returns ip with the low (32 - prefix_len) host bits cleared.

Input

  • ip: an IPv4 address as a uint32_t in host byte order.
  • prefix_len: the network prefix length, 0..32.

Output

The network base address: the top prefix_len bits of ip, with the rest zeroed.

Example

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)

Edge cases

  • prefix_len == 0: the mask is 0, so the result is 0.
  • prefix_len == 32: nothing is masked off; the address is returned unchanged.
  • Beware shifting by 32 (undefined behaviour) — special-case prefix_len == 0.

Input format

ip: host-order uint32_t IPv4 address; prefix_len: 0..32.

Output format

ip with the low (32 - prefix_len) bits cleared.

Constraints

Special-case prefix_len==0 to avoid the shift-by-32 UB.

Starter code

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