networking · intermediate · ~15 min
Build sin_addr from octets.
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.
Implement unsigned ipv4_to_be32(int a, int b, int c, int d) that returns (a << 24) | (b << 16) | (c << 8) | d.
a, b, c, d: the four octets (0..255 each).Returns the packed 32-bit value, a in the high byte.
ipv4_to_be32(127, 0, 0, 1) -> 0x7F000001
ipv4_to_be32(255, 255, 255, 255) -> 0xFFFFFFFF
unsigned before shifting to avoid signed-overflow undefined behaviour.Four integers a, b, c, d (the four octets).
The 32-bit value with a in the most-significant byte.
Cast each octet to unsigned before shifting; a occupies the high byte.
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.