Port numbers
The laptop has one IP address, 192.0.2.7, but three programs use the network: two browser tabs and a mail app. The IP address finds the machine. A second number, the port, finds the program.
A port is a 16-bit number, 0 to 65535, written in every TCP and UDP header. On the server, the web program listens on port 443 and the mail program on 587. Listening means waiting at that door.
IANA splits the numbers into three ranges. 0–1023 are well-known: 53 DNS, 80 HTTP, 443 HTTPS, 22 SSH, 25 SMTP. 1024–49151 are registered for other services. 49152–65535 are dynamic, for short-lived use.
Tab 1 asks the operating system for a connection. The OS lends it a free port from the dynamic range: 51514. Ports like this are ephemeral: given back when the connection closes.
Connections
Tab 1's first TCP message, a SYN, goes from 192.0.2.7:51514 to 203.0.113.10:443. Protocol, both IP addresses and both ports make the 5-tuple: the name of this connection.
Tab 2 also connects to 203.0.113.10:443, from port 52871. Only the source port differs from tab 1, but that is enough: two different 5-tuples, two separate connections.
The mail app gets port 60112 and connects to 587, where mail apps hand in outgoing mail. Same two machines, but other ports, so this is a third connection.
Delivery
The server's operating system reads the destination port to find the listening program, then the whole 5-tuple to find the exact connection. Port 443 now has two connections; port 587 has one.
The web server answers tab 2. The reply goes from 203.0.113.10:443 to 192.0.2.7:52871: both ends swapped. The laptop matches port 52871 and hands the data to tab 2, not tab 1.
A socket is a program's end of a connection: an IP address plus a port. Each program just reads and writes its own socket; the operating system adds the addresses and delivers by 5-tuple.
Ports and tuples, field by field
;; step 1/10 · many-programs · local ;; at tab 1 + tab 2 + mail app laptop 192.0.2.7 browser tab 1 wants a web page browser tab 2 wants another page mail app wants to send mail server 203.0.113.10 web server mail server the IP address alone cannot say which program a message is for
TCP and UDP count ports separately: TCP port 53 and UDP port 53 are different doors. DNS happens to use both. RFC 6335 sets aside 49152–65535 for dynamic ports, but each OS picks its own ephemeral range; Linux uses 32768–60999 by default. Mail apps hand in mail on port 587 (RFC 6409) or 465 with TLS from the start (RFC 8314). Port 25 is for mail servers passing mail to each other.