Sub topic 4
Sockets and Ephemeral Client Ports
This chapter assumes you know what an IP address is, understand the client-server model, can run commands in a terminal, and can read short Python scripts. It also assumes you have met the idea that a port number picks one service on a host. Here you will see how a connection is identified end to end, and why clients use temporary ports that nobody chose.
From port to socket
A port number alone does not identify a conversation. Port 443 on a server is used by thousands of clients at once. To tell them apart, the operating system works with sockets.
A socket endpoint is the combination of three things:
- an IP address
- a port number
- a transport protocol (TCP or UDP)
The same number in two protocols is two separate endpoints. TCP port 53 and UDP port 53 do not conflict, because the protocol is part of the identity.
In everyday speech, "socket" also means the object a program holds to send and receive data. The program asks the operating system for one, and the operating system gives it a handle. In this chapter, "endpoint" means the address triple, and "socket" means the handle your program uses.
The five-tuple
A TCP connection is identified by two endpoints. Together with the protocol, they form a five-tuple:
| Field | Example |
|---|---|
| Protocol | TCP |
| Source IP | 192.0.2.50 |
| Source port | 52814 |
| Destination IP | 198.51.100.7 |
| Destination port | 443 |
The operating system keeps a table of connections keyed by this tuple. When a packet arrives, the system reads these fields and delivers the data to the matching socket.
This explains how a server handles many clients on one port. Every client has a different source IP, a different source port, or both, so each tuple is unique. The server does not need a separate port for each client. It listens on one port and accepts connections that all share the same destination endpoint.
Listening sockets and connected sockets
A server's role in the socket API has two stages.
- The server creates a socket, binds it to an address and port, and calls listen. This is the listening socket. It waits for new connections and does not carry data.
- When a client connects, accept returns a new connected socket for that one client. The listening socket stays open and keeps accepting.
So a web server with 1,000 clients has one listening socket on port 443 and 1,000 connected sockets. All of them report local port 443. Only the full tuple differs.
UDP works differently. It has no connection and no accept step. One UDP socket bound to a port receives datagrams from any sender, and each datagram carries its source address and port so the program can reply.
Ephemeral client ports
A client does not need a well-known port, because nobody connects to it first. It starts the conversation. So when a client calls connect without binding, the operating system picks an unused local port. This is an ephemeral port: a short-lived port assigned automatically from a dynamic range and released when the connection ends.
The server learns the client's port from the incoming packet and sends replies back to it. The ephemeral port is how the response finds the right program on the client.
Default ranges differ by system:
| System | Default ephemeral range |
|---|---|
| IANA suggestion | 49152 to 65535 |
| Linux | 32768 to 60999 |
| Windows (Vista and later) | 49152 to 65535 |
| macOS | 49152 to 65535 |
On Linux, you can read the current range:
cat /proc/sys/net/ipv4/ip_local_port_rangeThe output is two numbers, the lowest and highest port. An administrator can change them with sysctl net.ipv4.ip_local_port_range.
Seeing both ends in Python
This script connects to a web server and prints both endpoints of the socket.
import socket
with socket.create_connection(("example.com", 80), timeout=5) as s:
print("local :", s.getsockname())
print("remote:", s.getpeername())A typical result looks like this:
local : ('192.0.2.50', 52814)
remote: ('203.0.113.9', 80)The remote port is 80 because you asked for it. The local port is different on every run, because the operating system chose it. Run the script several times and watch the local port change. Some systems pick ports at random, and others count upward. Random choice is a defense against attackers who try to guess a port and inject packets into a connection.
Port 0 and explicit binding
If a program binds to port 0, it asks the operating system to choose a free port. This is useful in tests and in programs that need a listening port but do not care which one.
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
print("OS chose port", s.getsockname()[1])A client can also bind to a specific source port before connecting. This is rare. Some old protocols required it, and it can make firewall rules simpler, but it risks a conflict if the port is already in use.
Edge cases and common errors
Address already in use
A server restarts and fails with "Address already in use" even though no process is listening. The cause is the TCP TIME_WAIT state. After a connection closes, the side that closed first keeps the tuple reserved for a short time (commonly 60 seconds on Linux) so late packets from the old connection are not mistaken for a new one. Binding the listening port can fail while old connections sit in this state.
The usual fix is to set the SO_REUSEADDR option before binding:
import socket
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("0.0.0.0", 8080))
srv.listen()
print("listening on", srv.getsockname())
srv.close()Ephemeral port exhaustion
A client opens many short connections to the same server address and port. Each one uses a local port, and each closed connection leaves a TIME_WAIT entry. The tuple differs only in the source port, so the client can use at most as many simultaneous and recently closed connections as there are ports in its range. With the Linux default, that is about 28,000 for one destination. When the range runs out, connect fails with "Cannot assign requested address".
Common remedies:
- reuse connections with keep-alive or a connection pool
- widen the ephemeral range
- spread load across more destination addresses
Firewalls and return traffic
A firewall rule that allows outgoing connections to port 443 must also allow the replies, which arrive at an ephemeral port. Writing a rule for each possible ephemeral port is impractical. Stateful firewalls solve this by tracking connections and allowing replies to traffic they saw leave. Chapter 15 covers rules in more detail.
Ephemeral ports can collide with services
If a service listens on a port inside the ephemeral range, such as 40000, the operating system may already have given that port to an outgoing connection. The service then fails to start at random. Keep service ports out of the ephemeral range, or reserve them with net.ipv4.ip_local_reserved_ports on Linux.
Checking sockets from the command line
The ss command lists sockets. The flags below show TCP sockets with numeric ports and no name lookup:
# Listening sockets
ss -tln
# Established connections, including the client's ephemeral port
ss -tn state establishedIn the second command, the local address of an outgoing connection shows an ephemeral port, and the peer address shows the service port, such as 443.
Summary of key points
- A socket endpoint is IP address, port and protocol.
- A TCP connection is identified by the five-tuple, so one server port can serve many clients.
- A server has one listening socket and one connected socket per client.
- Clients get ephemeral ports from the operating system, and the range varies by platform.
- Port 0 asks the operating system to choose a port.
- TIME_WAIT and a limited ephemeral range explain two common failures: "Address already in use" and port exhaustion.
Exercise
A client at 192.0.2.50 has two open TCP connections to the same web server at 198.51.100.7 on port 443. The client's source ports are 52814 and 52815. Why does the server not confuse the two connections, and what would happen if both used the same source port?
Show answer
The server identifies each connection by its five-tuple (protocol, source IP, source port, destination IP, destination port). The two connections differ in the source port, so their tuples are distinct and each packet goes to the correct connected socket. If both used the same source port, the tuples would be identical, which is not allowed. The operating system would refuse to create the second connection from that source port to the same destination.
Exercise
A load-testing script opens thousands of short TCP connections per second to one server on port 8080 and starts failing with "Cannot assign requested address". Name the cause and two ways to fix it.
Show answer
The client is running out of ephemeral ports. Closed connections stay in TIMEWAIT and hold their source ports, and for a single destination address and port the source port is the only part of the tuple that can vary. Fixes include reusing connections (keep-alive or a pool), widening the ephemeral port range with net.ipv4.iplocalportrange, or sending the test to several server addresses or ports.