sockets · advanced
Sockets: Key Options - SO_REUSEADDR, TCP_NODELAY, Keepalive
setsockopt tunes socket behavior, and a few options come up constantly. SO_REUSEADDR, set before bind(), lets a server re-bind its port immediately even when old connections linger in TIME_WAIT — without it a restart fails with EADDRINUSE — and also permits binding a specific address alongside a wildcard socket; the distinct SO_REUSEPORT instead lets multiple sockets share one port so the kernel load-balances accepts across threads or processes. TCP_NODELAY disables Nagle's algorithm, which by default coalesces small outgoing writes to reduce packet overhead but adds latency and, combined with delayed ACKs, causes the infamous ~40ms request/response stall; latency-sensitive systems such as RPC, games, and especially HFT order paths set TCP_NODELAY, while bulk transfers can leave Nagle on. SO_KEEPALIVE sends probes on idle connections to detect a dead peer, since a silently dropped TCP connection otherwise appears alive indefinitely (application-level heartbeats are often more responsive than the slow keepalive defaults). Other important options include SO_RCVBUF/SO_SNDBUF to size kernel buffers for high bandwidth-delay-product links, SO_LINGER to control whether close() blocks to flush data or sends an abortive RST, SO_RCVTIMEO/SO_SNDTIMEO for per-call timeouts on blocking sockets, and getsockopt with SO_ERROR to retrieve the result of a non-blocking connect.
Key socket options: SO_REUSEADDR (before bind) rebinds through TIME_WAIT (avoids EADDRINUSE); TCP_NODELAY disables Nagle for low-latency small messages (HFT/RPC); SO_KEEPALIVE detects dead peers; SO_*BUF, SO_LINGER, SO_*TIMEO tune buffers, close behavior, and timeouts.
The code
int yes = 1;setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); // before bind()setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof yes); // disable Naglesetsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof yes); // detect dead peers
// SO_RCVBUF / SO_SNDBUF : socket buffer sizes// SO_LINGER : control close() behavior// SO_RCVTIMEO/SNDTIMEO : per-call timeoutsWhat this lesson walks through
- 01SO_REUSEADDR — rebind through TIME_WAIT
- 02TCP_NODELAY — turn off Nagle's algorithm
- 03Gotcha — the options that bite, and when to set them
- 04Keepalive, buffers, linger, timeouts
Set SO_REUSEADDR (before bind) so a server can re-bind its port immediately even if old connections sit in TIME_WAIT — without it, a restart fails with EADDRINUSE. It also lets you bind to a specific address while another socket uses the wildcard. (SO_REUSEPORT is different: it lets MULTIPLE sockets share one port for kernel-load-balanced accept across threads/processes.)
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Sockets: Key Options - SO_REUSEADDR, TCP_NODELAY, Keepalive and 100+ animated C++ interview lessons.