Socket Options: getsockopt(), setsockopt() & SO_REUSEADDR
Idea in plain words
Socket options are inspected and configured using getsockopt() and setsockopt() at SOL_SOCKET, IPPROTO_IP, or IPPROTO_TCP levels.
Exam tip
High-yield exam topic (High).
Explanation
Socket options modify transport layer behaviors. When a TCP server terminates abruptly while active client connections exist, the local socket enters the TIME_WAIT state for 2MSL. If the server restarts immediately, bind() fails with EADDRINUSE. Enabling SO_REUSEADDR signals the kernel to permit socket rebinding. Similarly, Nagle's algorithm coalesces small packets to optimize network bandwidth, but introduces unwanted delay in interactive protocols; setting TCP_NODELAY forces immediate segment transmission.
Key points
- SO_REUSEADDR permits a server to bind to an IP/port currently in the TIME_WAIT state.
- SO_KEEPALIVE periodically probes idle TCP connections to detect severed client links.
- SO_RCVBUF and SO_SNDBUF set transport socket buffer capacities to optimize throughput over high-bandwidth-delay product paths.
- TCP_NODELAY disables Nagle's algorithm to eliminate latency for interactive or packet-sensitive real-time traffic.
Example
Example
Retrieving TCP send buffer size: int val; socklen_t len = sizeof(val); getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &val, &len);
Code examples
// Enable SO_REUSEADDR on listening socket
int on = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
// Disable Nagle's algorithm for low-latency transmission
int nodelay = 1;
setsockopt(connfd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
Exam questions
- [8 Marks] Explain the purpose of getsockopt() and setsockopt(). Discuss SO_REUSEADDR, SO_KEEPALIVE, and TCP_NODELAY with code snippets.
- [4 Marks] What is Nagle's algorithm? In which scenarios should it be disabled using TCP_NODELAY?