In a TCP connection, what's the role of the source port vs the destination port?
Destination port = the well-known service (e.g. 443 for HTTPS). Source port = a random ephemeral port the OS picked, used to demultiplex multiple connections from the same client.
Roles:
| Port | Range | Purpose |
|---|---|---|
| Destination | 0-1023 (well-known) | Identifies the service: 80=HTTP, 443=HTTPS, 22=SSH, 25=SMTP, 21=FTP, 53=DNS |
| Source | 49152-65535 (ephemeral) | Random per-connection — lets the client distinguish replies |
Why the source port matters:
Imagine two browser tabs to the same server (google.com:443):
Tab 1 → 142.250.x.x:443 from your_ip:54881
Tab 2 → 142.250.x.x:443 from your_ip:54882
Both go to the same destination, but the source ports differ. When responses come back, the OS uses the 4-tuple (src_ip, src_port, dst_ip, dst_port) to route each packet to the correct socket.
The 4-tuple = unique connection ID:
A TCP connection is uniquely identified by:
(client IP, client port, server IP, server port)
Change any one → new connection. This is how a server can handle thousands of simultaneous clients on port 443.
Source port is random for security:
If the source port were predictable, attackers could blindly inject packets into your session. Modern OSes randomize.
Implication for NAT:
Home routers use NAT, which rewrites source ports as packets leave. This is how multiple devices behind one public IP can browse simultaneously — the router maps each (internal_ip, internal_port) to a unique (public_ip, mapped_port).
Tip: When troubleshooting "connection refused" vs "timeout", check whether the destination port is what you expect. Port 80 closed but port 443 open just means there's no plain-HTTP server running, which is fine.
Go deeper:
Port (computer networking) (Wikipedia) — well-known vs dynamic ranges and the source/destination endpoint roles.
Ephemeral port (Wikipedia) — the random high-numbered source ports that demultiplex a client's many connections.