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
| Range | Name | Notes |
|---|---|---|
| 0 to 1023 | Well-known (system) | Binding needs root or CAP_NET_BIND_SERVICE on Linux |
| 1024 to 49151 | Registered (user) | Assigned by IANA to applications |
| 49152 to 65535 | Dynamic (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
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().
They will ask next
What is the difference between SO_REUSEADDR and SO_REUSEPORT?
SO_REUSEADDR lets a server bind its port again while old connections on it sit in TIME_WAIT, so a restart does not fail with "address already in use". SO_REUSEPORT (Linux 3.9 and later) lets several sockets listen on the same port and the kernel spreads new connections across them.
Is there a 65,535 connection limit on a server?
No. 65,535 is the number of ports, and a server uses one. The limit per client IP talking to one server port is about the size of the client's ephemeral range. Total connections are bounded by memory.
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.