Socket Address Structures, Endianness & Address Conversion
Idea in plain words
struct sockaddr_in represents IPv4 socket addresses: sin_family (AF_INET), sin_port (in_port_t), sin_addr (struct in_addr).
Exam tip
High-yield exam topic (High).
Explanation
Because networks interconnect heterogeneous processor architectures, internet protocols standardize on Big-Endian (most significant byte transmitted first). Socket addresses must convert 16-bit port numbers and 32-bit IP addresses into network byte order before invoking bind() or connect(). In C, socket system calls take pointer arguments of type 'struct sockaddr *' along with a socklen_t length parameter. For functions where the kernel returns an address (accept(), getsockname(), recvfrom()), the length argument is a value-result pointer that passes the buffer capacity on entry and receives the actual byte count on return.
Key points
- struct sockaddr is the generic socket address structure used as a cast target in socket system calls.
- Byte ordering: Network Byte Order is Big-Endian; Host Byte Order may be Little-Endian (x86) or Big-Endian.
- Endian conversion functions: htons() (host to network short), htonl() (host to network long), ntohs(), ntohl().
- Address conversion: inet_pton() (presentation to numeric) and inet_ntop() (numeric to presentation) support both IPv4 and IPv6.
Example
Example
Converting an IPv4 string to binary network format using inet_pton(AF_INET, '127.0.0.1', &addr.sin_addr). To convert back for printing: char str[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &addr.sin_addr, str, sizeof(str));
Code examples
#include <netinet/in.h>
#include <arpa/inet.h>
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8080); // Host to Network Short
inet_pton(AF_INET, "192.168.1.100", &servaddr.sin_addr); // Presentation to Network Numeric
Exam questions
- [7 Marks] Explain IPv4 socket address structure (sockaddr_in) and generic socket address structure (sockaddr). What is a value-result argument?
- [5 Marks] Differentiate between Little-Endian and Big-Endian byte orders. Why are htons() and ntohs() necessary?