TCP clients & servers
Write a TCP echo server and client that handle framing and disconnects.
By Invicly Tech, , in Linux System Programming. About 13 minutes to read.
In short
TCP provides a reliable, ordered byte stream between two endpoints, set up with a three-way handshake. A server binds, listens and accepts connections, getting a new descriptor per client. Because TCP is a stream, your protocol must define message boundaries, for example with newlines or length prefixes.
Explained simply
TCP is like a phone call between two programs. First the call is set up, then both sides can talk, and every byte arrives in order with nothing missing. If a packet gets lost on the way, TCP quietly sends it again.
A TCP server needs two kinds of sockets. The listening socket is the receptionist: it only waits for new callers. Each time a caller arrives, accept hands you a new socket just for that conversation, while the receptionist keeps waiting for the next one.
One surprise: TCP sends a stream of bytes, not messages. If the client sends "hello" and then "world", the server might read "hellowor" and then "ld". Your program has to mark where each message ends, for example with a newline, or by sending the length first.
Connections also end, sometimes politely and sometimes not. A good server notices a closed connection, cleans it up, and never crashes because a client disappeared halfway through.
Press Play on a diagram to walk through it one step at a time.
- Client to Server: SYN (client calls connect)1SYN (client calls connect)
- Server to Client: SYN-ACK2SYN-ACK
- Client to Server: ACK (connection queued for accept)3ACK (connection queued for accept)
- Client to Server: Data: request bytes4Data: request bytes
- Server to Client: Data: response bytes5Data: response bytes
- Client to Server: FIN (client closes)6FIN (client closes)
- Server to Client: ACK, then FIN when the server closes7ACK, then FIN when the server closes
- n > 0
- Some bytes moved, maybe fewer than asked
- Loop for the rest
- recv == 0
- Peer closed politely (FIN)
- Close and free the connection
- -1, EINTR
- Interrupted by a signal
- Retry the call
- -1, EAGAIN
- Non-blocking socket not ready
- Wait for readiness
- -1, ECONNRESET or EPIPE
- Connection is dead
- Close it; keep serving others
In depth
The handshake and the two kernel queues
When a client calls connect, its kernel sends a SYN. The server's kernel answers with SYN-ACK and keeps a small record in the SYN queue (half-open connections). When the client's ACK arrives, the connection is complete and moves to the accept queue. All of this happens inside the kernel, before your program calls accept. accept simply takes the oldest finished connection off that queue.
The backlog argument to listen sets the size of the accept queue, capped by net.core.somaxconn. If your program is too slow to accept and the queue fills, new clients see delays or timeouts. You can watch it with ss -ltn: for a listening socket, Recv-Q is how many connections wait right now and Send-Q is the backlog limit. Under a SYN flood the SYN queue fills instead, and Linux falls back to SYN cookies (net.ipv4.tcp_syncookies), which encode the state in the sequence number.
- 1Client SYN
connect() starts the handshake
- 2SYN queue
Server kernel replies SYN-ACK
- 3Client ACK
Connection is now established
- 4Accept queue
Waits here; size set by the backlog
- 5accept()
Your program gets a new descriptor
TIME_WAIT and SO_REUSEADDR
The side that closes a connection first enters the TIME_WAIT state. It stays there for twice the maximum segment lifetime, fixed at 60 seconds on Linux, so that delayed packets from the old connection cannot be mistaken for a new one using the same addresses and ports.
This bites servers on restart. You stop the server, and its recent connections sit in TIME_WAIT on port 7000. The new process calls bind on port 7000 and fails with EADDRINUSE: Address already in use. Setting SO_REUSEADDR to 1 before bind allows the bind as long as no socket is actually listening on that port. Every TCP server should set it.
Do not confuse it with SO_REUSEPORT, which lets several sockets bind the exact same port at once, with the kernel spreading new connections across them. That is used to run one accept loop per CPU core.
- ss -tan state time-wait lists sockets in TIME_WAIT
- Set SO_REUSEADDR after socket and before bind
- SO_REUSEPORT is for load-sharing, not for restarts
Framing messages on a byte stream
TCP keeps the order of bytes but not the boundaries of your sends. One send may arrive in several recv calls, and several sends may arrive in one. So every protocol needs a framing rule.
Delimiter framing ends each message with a marker, usually a newline. It suits text protocols such as SMTP, Redis and chat. The receiver appends incoming bytes to a buffer and handles each complete line, keeping any partial line for later. You must cap the line length, or a client that never sends a newline can fill your memory.
Length-prefix framing sends the size first, often as a 4-byte big-endian integer, then exactly that many bytes. It handles binary data and lets the receiver allocate the right buffer. Again, check the length against a maximum before allocating.
A related detail: Nagle's algorithm delays small writes to combine them. For request-response protocols that send small messages, set TCP_NODELAY, or better, build the whole message and send it in one call.
- Text lines like PING
- Easy to test with nc
- Must escape newlines in data
- Cap line length
- 4-byte size, then payload
- Any binary data
- Read header, then exact body
- Cap the declared size
Disconnects, ECONNRESET and SIGPIPE
recv returning 0 means the peer closed its side politely (it sent a FIN). recv returning -1 with ECONNRESET means the connection was reset (an RST), for example because the client crashed or closed with unread data. Both mean: close this socket and free its state.
Writing is trickier. If the peer has gone, your first send may still succeed, because it only copies bytes into the kernel's send buffer. The peer's kernel then answers with RST, and the next send triggers SIGPIPE, whose default action kills your whole server. Ignore it once at startup with signal(SIGPIPE, SIG_IGN), or pass MSG_NOSIGNAL to every send. Then the call returns -1 with EPIPE instead, and you just close that connection.
A peer that vanishes without any packet (cable pulled, laptop asleep) is never noticed if you only wait to read. Use application timeouts or heartbeats, or TCP keepalive (SO_KEEPALIVE), whose default only starts probing after 2 hours of silence.
- recv == 0: orderly close
- ECONNRESET or EPIPE: close the socket, do not exit
- shutdown(fd, SHUT_WR) sends FIN but still lets you read
Iterative servers and their limit
The explainer's echo server is iterative: it serves one client completely before calling accept again. That is fine for learning and for tiny admin tools, but one slow client blocks everyone. A client that connects and sends nothing freezes the whole server.
There are three classic ways out. Fork per connection: the parent accepts and forks, the child serves one client and exits; the parent must close its copy of the client socket and reap children. Thread per connection: same idea with threads, cheaper, but every shared structure needs locking. Event loop: one thread watches all sockets with epoll and only touches the ones that are ready, which the next topics cover. Each step trades simpler code for higher capacity.
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Explain the TCP three-way handshake~1h
- 2Write an iterative echo server~1h
- 3Set SO_REUSEADDR before bind~1h
- 4Frame messages on a byte stream~1h
- 5Handle disconnects and EPIPE~1h
Key points
- Set SO_REUSEADDR before bind so restarts do not fail with EADDRINUSE.
- accept returns a new connected socket; the listening socket keeps listening.
- recv returning 0 means the peer closed the connection.
- One send can arrive as several recvs and vice versa, so frame your messages.
- Ignore SIGPIPE or use MSG_NOSIGNAL so writing to a closed peer returns EPIPE.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void) {
int s = socket(AF_INET, SOCK_STREAM, 0), one = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(7000), .sin_addr.s_addr = htonl(INADDR_ANY) };
if (bind(s, (struct sockaddr *)&a, sizeof a) < 0 || listen(s, 64) < 0) return 1;
for (;;) {
int c = accept(s, NULL, NULL);
char buf[1024]; ssize_t n;
while ((n = recv(c, buf, sizeof buf, 0)) > 0) send(c, buf, n, 0);
close(c);
}
}Iterative echo server on port 7000; test with nc localhost 7000.
Restart fails with Address already in use
You stop your echo server and start it again within a minute, and bind fails. Step 1: look at the port. The old connections are in TIME_WAIT because the server closed them first. Step 2: confirm nothing is still listening; if a LISTEN line remains, an old process is still running, and SO_REUSEADDR will not help. Step 3: add SO_REUSEADDR before bind and rebuild. Step 4: restart; bind now succeeds even with TIME_WAIT entries present.
./echo_server
# bind: Address already in use
ss -tan '( sport = :7000 )'
# State Recv-Q Send-Q Local Address:Port Peer Address:Port
# TIME-WAIT 0 0 127.0.0.1:7000 127.0.0.1:51234
ss -ltnp '( sport = :7000 )' # empty: no process is listening
# fix: setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one) before bindReading one length-prefixed message
Our protocol sends a 4-byte big-endian length, then the payload. Step 1: read exactly 4 bytes with a loop, because recv may return fewer. Step 2: convert with ntohl and refuse sizes above a limit, so a bad client cannot make us allocate gigabytes. Step 3: allocate and read exactly that many bytes. Step 4: a return of 0 from recv in the middle means the peer closed early, which we report as an error.
static int recv_all(int fd, void *buf, size_t n) { /* 0 ok, -1 error or EOF */
for (size_t got = 0; got < n; ) {
ssize_t r = recv(fd, (char *)buf + got, n - got, 0);
if (r > 0) got += (size_t)r;
else if (r < 0 && errno == EINTR) continue;
else return -1; /* 0 = peer closed early */
}
return 0;
}
char *recv_msg(int fd, uint32_t *len) {
uint32_t be;
if (recv_all(fd, &be, 4) < 0 || (*len = ntohl(be)) > 1 << 20) return NULL;
char *m = malloc(*len ? *len : 1);
if (m && recv_all(fd, m, *len) < 0) { free(m); m = NULL; }
return m;
}Quick reference
- Server: socket, setsockopt SO_REUSEADDR, bind, listen, then accept in a loop
- ss -ltn: Recv-Q = connections waiting for accept, Send-Q = backlog
- TIME_WAIT lasts 60 seconds on Linux; it is normal, not a leak
- signal(SIGPIPE, SIG_IGN) once, or send(..., MSG_NOSIGNAL) every time
- recv == 0 means the peer closed; ECONNRESET means it reset
- TCP has no message boundaries: frame with newlines or a length prefix
- setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one) disables Nagle
- nc localhost 7000 is a quick test client; nc -l 7000 a quick test server
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run the explainer's echo server, connect with nc, then stop and restart the server right away. Watch the TIME_WAIT entries with ss, and confirm SO_REUSEADDR makes the restart work.
- Exercise 2medium
Make the echo server robust: ignore SIGPIPE, check every call, send the whole buffer with a send_all loop, and close the client on recv 0, ECONNRESET or EPIPE without exiting.
- Exercise 3hard
Turn the iterative echo server into a fork-per-connection server. Make sure the parent closes its copy of the client socket and that zombies are reaped.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why does my server say Address already in use after a restart?
- Old connections on that port are in TIME_WAIT for 60 seconds. Set SO_REUSEADDR before bind. If ss -ltnp still shows a LISTEN entry, another process really is using the port.
- Why do I receive half a message?
- TCP does not keep message boundaries, so a recv returns whatever bytes have arrived. Keep a buffer per connection and only handle a message once its whole frame is there.
- How do I detect that a client is gone?
- recv returns 0 or fails with ECONNRESET when the peer closes or resets. If the peer just vanishes, nothing arrives at all, so use read timeouts, heartbeats or TCP keepalive.
- What backlog should I pass to listen?
- Something like 128 to 4096. The kernel caps it at net.core.somaxconn. A larger backlog only helps with bursts; if accept is slow all the time, fix the accept loop instead.