Octet

What is a socket, and how can one web server on port 443 serve thousands of clients at once?

Show the answer

Say this first

A socket is the operating system's handle for one end of a conversation: protocol, local IP and port, and for a connected TCP socket the remote IP and port too. A TCP connection is identified by the five-tuple, so the server's listening socket on 443 can accept any number of connections: each new one has the same local address and port and a different client address or client port. Clients pick their source port from the ephemeral range.

Go deeper

Port ranges

RangeNameNotes
0 to 1023Well-known (system)Binding needs root or CAP_NET_BIND_SERVICE on Linux
1024 to 49151Registered (user)Assigned by IANA to applications
49152 to 65535Dynamic (private)IANA's suggested ephemeral range

Defaults differ: Linux uses 32768 to 60999 (net.ipv4.ip_local_port_range), Windows uses 49152 to 65535.

What really limits connections

On the server: memory and file descriptors, not ports. One port can carry millions of connections. On the client: the number of free source ports for each destination IP and port, because the four-tuple must be unique. Behind PAT, every inside host shares the outside address's ports, which is where port exhaustion usually shows up.

Listening versus accepted sockets

Shell
ss -tn state established '( sport = :443 )'

Every line has local port 443 and a different peer. The single LISTEN socket is separate and only queues new connections for the application to accept().

Traps

  • Saying a server "runs out of ports" because it has many clients. Clients run out of source ports; servers run out of memory or file descriptors.
How did you do?Book 1.4 SoftwareBook 5.1 Simple Demultiplexor (UDP)