Notes
The server
Here is the whole server. socket creates a TCP endpoint, AF INET for IP version four, SOCK STREAM for TCP. bind attaches it to an address and port. listen tells the kernel to accept connections for us. Then a loop: accept waits for a client and returns a new socket just for that conversation. We receive up to a thousand and twenty four bytes, send them back with echo in front, and close. That is a real, working TCP server.
s = socket(AF_INET,
SOCK_STREAM)
s.setsockopt(SOL_SOCKET,
SO_REUSEADDR, 1)
s.bind(("127.0.0.1", 9000))
s.listen(128)
while True:
c, addr = s.accept()
c.sendall(b"echo: " +
c.recv(1024))
c.close() The client
The client is even shorter. create connection resolves the address and runs the TCP handshake, the connect call. Then it sends hello shoprung, waits for the reply and closes. Our run printed echo hello shoprung, with connect taking two point eight milliseconds and the whole exchange three. The client got a random local port from the kernel, the forty thousand range you saw in tcpdump.
c = create_connection(
("127.0.0.1", 9000))
c.sendall(b"hello shoprung")
print(c.recv(1024))
c.close()
echo: hello shoprung
connect 2.8 ms,
total 3.0 ms Behind the scenes
Behind the scenes, the kernel does the handshake on its own, before your code even calls accept. Finished connections wait in a queue whose size listen sets, the backlog. accept takes one out and returns a new connection socket; the listening socket keeps listening. If your code is too slow to accept, the queue fills and new SYNs are dropped, which clients see as slow or timed out connections even though the server looks fine.
- kernel completes SYN/SYN-ACK/ ACK by itself
- finished connections wait in the accept queue (backlog)
- accept() takes one out and returns a NEW socket
- listening socket keeps listening
- backlog full → SYNs dropped
One at a time
Now break it. Client one connected and sent nothing. Our server sat in recv, waiting for client one. Client two connected, which succeeded because the kernel did the handshake, sent hi, and waited for an answer that never came: it timed out after two seconds. A server that handles one connection at a time is stuck behind its slowest client. The fixes are threads, processes, or an event loop, the next episode.
client 1 connects, sends nothing server is stuck in recv() for client 1 client 2 connects (kernel accepts it) and sends "hi" → TimeoutError after 2,002 ms one loop, one client at a time
Address already in use
Next, the error every engineer meets. With the server running, a second program tried to bind port nine thousand and got errno ninety eight, address already in use. Only one listener can own an address and port. ss minus t l n p shows which process holds it, often an old copy still running. The SO REUSEADDR option in our server is different: it lets a restarted server bind even while old connections sit in TIME WAIT.
>>> s.bind(("127.0.0.1",
... 9000))
OSError: [Errno 98] Address
already in use
$ ss -tlnp | grep :9000
shows who holds it
SO_REUSEADDR: rebind while
old TIME-WAITs remain Which address?
Which address you bind matters. One two seven dot zero dot zero dot one means only programs on the same machine can connect. Zero dot zero dot zero dot zero means every interface, so the whole network can reach it if firewalls allow. Inside a container, binding to loopback means only the container itself can connect, so port publishing appears broken. Works locally but not from outside is very often this.
- 127.0.0.1 only this machine can connect
- 0.0.0.0 every interface: LAN, VPC, the internet if allowed
- in a container, 127.0.0.1 means the container only → "works locally, not from outside": check the bind
Everything is a file
Remember from part one, everything is a file. Each socket uses one file descriptor, and processes have a limit. Our lab machine allowed twenty thousand; many systems default to one thousand and twenty four. A busy server or a connection leak hits the limit and fails with too many open files. Raise it with LimitNOFILE in a systemd unit or ulimit settings for containers, and count a process's descriptors in proc slash PID slash fd.
every socket = 1 fd $ ulimit -n our lab machine: 20000 common default: 1024 too many → "Too many open files" (EMFILE) systemd: LimitNOFILE= containers: --ulimit $ ls /proc/PID/fd | wc -l
Common mistakes
Mistakes. Servers that serve one client at a time. No timeouts, so one silent client hangs a worker forever. Binding loopback inside a container. A tiny backlog that drops connections in bursts. Low file descriptor limits. And a subtle one: assuming one recv returns one whole message. TCP is a byte stream; real protocols add lengths or delimiters to frame messages.
- one-at-a-time servers
- no timeouts on recv
- binding 127.0.0.1 in a container
- tiny backlog under bursts
- low fd limits
- assuming one recv() = one message (TCP is a stream: frame your data)
Say it like this
In the interview: the server calls socket, bind and listen. The kernel completes handshakes on its own and queues them in the backlog, and accept hands back a new socket for each client while the listening socket keeps listening. Each connection uses a file descriptor. To serve many clients I use threads, processes or an event loop with epoll, with timeouts, a sensible backlog and raised file limits.
- "The server calls socket, bind, listen. The kernel completes
- handshakes and queues them in the backlog; accept returns a new socket per client. Each uses an fd. To serve many clients I use
- threads or an event loop, set
- timeouts and raise the limits."