networking · intermediate · ~15 min

Pack a dotted quad into a 32-bit address

Build sin_addr from octets.

Challenge

A sockaddr_in stores an IPv4 address as one 32-bit big-endian word. Pack a dotted quad a.b.c.d into that word, with a in the most-significant byte.

Task

Implement unsigned ipv4_to_be32(int a, int b, int c, int d) that returns (a << 24) | (b << 16) | (c << 8) | d.

Input

  • a, b, c, d: the four octets (0..255 each).

Output

Returns the packed 32-bit value, a in the high byte.

Example

ipv4_to_be32(127, 0, 0, 1)         ->   0x7F000001
ipv4_to_be32(255, 255, 255, 255)   ->   0xFFFFFFFF

Rules

  • Cast each octet to unsigned before shifting to avoid signed-overflow undefined behaviour.

Input format

Four integers a, b, c, d (the four octets).

Output format

The 32-bit value with a in the most-significant byte.

Constraints

Cast each octet to unsigned before shifting; a occupies the high byte.

Starter code

unsigned ipv4_to_be32(int a, int b, int c, int d) {
    /* TODO */
    return 0;
}

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