DEVOPS, SRE AND CLOUD · PART 2 · NETWORKING FOR DEVOPS · SOCKETS · 34 OF 187

Socket Programming: A TCP Server and Client in Python

Write the TCP server behind every web app, in nine lines of Python: socket, bind, listen, accept, recv, send, close, and the client side with connect. Then see what goes wrong for real: "Address already in use", a server that handles one client at a time (a second client timed out after 2,002 ms while a slow one held it), the listen backlog, file descriptor limits and why 0.0.0.0 differs from 127.0.0.1.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 11

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • socket
  • bind
  • listen
  • accept
  • recv/send
  • close
  • backlog
  • errno 98
  • 0.0.0.0 vs 127.0.0.1
  • fd limits

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.

echo_server.py
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.

echo_client.py (our run)
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.

What happens
  • 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.

Our test
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.

Second bind (ours)
>>> 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.

bind address
  • 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.

Limits
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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1Which system calls does a TCP server use?

socket() to create it, bind() to an address and port, listen() to accept connections, accept() to get a per-client socket, then recv()/send() and close().

Q2What does "Address already in use" mean?

Another socket is already bound to that address and port (often an old process). Find it with ss -tlnp; SO_REUSEADDR helps only with lingering TIME-WAIT.

Q3What is the listen backlog?

The kernel queue of completed connections waiting for accept(); if it overflows, new connection attempts are dropped and clients see delays or timeouts.

Q4What is the difference between binding to 0.0.0.0 and 127.0.0.1?

127.0.0.1 accepts only local connections; 0.0.0.0 listens on all interfaces, so other machines (and containers' port mappings) can reach it.

Q5What causes "Too many open files"?

The process hit its file descriptor limit; every socket and file uses one. Raise LimitNOFILE/ulimit -n and check for connection leaks.

Q6Why can one recv() not be trusted to return one message?

TCP is a byte stream with no message boundaries; data may arrive split or merged, so protocols use length prefixes or delimiters.