CloudAcademia
EN

Networking · Module 08 · Transport Layer: TCP, UDP and Ports

Transport Layer: TCP, UDP and Ports

Lesson50 minBeginnerMarkdown

Showing raw Markdown: the renderer could not load.

## Why this matters
You deploy a small web application on a server and try it from your laptop. The browser says *connection refused*. A colleague tries a minute later from home and gets *connection timed out*. Both messages mean "it doesn't work", but they point to completely different problems. The first one says the server answered: "nothing is listening here". The second says nothing answered at all, so the packets were dropped somewhere on the way. If you can tell them apart, you know whether to look at the application or at the firewall.

The same knowledge explains everyday puzzles. Why does a video call keep going through a bad Wi-Fi connection while a file download stalls? Why does a busy server show thousands of connections in a state called `TIME_WAIT`? Why can one server run a web server and a Secure Shell (SSH) server on the same Internet Protocol (IP) address? All the answers live at the transport layer, home of the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP), and the subject of this lesson.

## Learning objectives
- Explain the transport layer's job and how ports identify processes (well-known, registered and ephemeral ports).
- Compare TCP and UDP (connections, reliability, ordering, overhead) and choose one for a given application.
- Describe the TCP three-way handshake, connection teardown, sequence and acknowledgement numbers, retransmission and flow control.
- Identify listening sockets and connection states (LISTEN, ESTABLISHED, TIME_WAIT) with `ss` or `netstat`.
- Troubleshoot "connection refused" versus "connection timed out".

## Key concepts

### Ports: from a host to a process
An IP address gets a packet to the right building. It doesn't say which flat. A server at `203.0.113.80` may run a web server, an SSH server and a database at the same time, and your laptop may have twenty browser tabs open. Something has to decide which program each packet belongs to.

That is the job of the **transport layer** (Layer 4 in the [OSI model](../04-osi-model/lesson.md)). It carries data between *processes*, not just between hosts. To do that, it labels every message with two **port** numbers: a source port and a destination port. A port is a 16-bit number, from 0 to 65535. A program that wants to receive traffic asks the operating system for a port; from then on, the operating system hands it everything that arrives for that port. Sorting incoming data by port is called **demultiplexing**; mixing many programs' data onto one IP address is **multiplexing**.

Port numbers are split into three ranges by RFC 6335, and the Internet Assigned Numbers Authority (IANA) keeps the registry:

| Range | Name in RFC 6335 | Also called | Used for |
|---|---|---|---|
| 0–1023 | System ports | **Well-known ports** | Standard services: 22 SSH, 53 Domain Name System (DNS), 443 HTTP Secure (HTTPS) |
| 1024–49151 | User ports | **Registered ports** | Services registered with IANA: 3389 Remote Desktop Protocol (RDP), 5432 PostgreSQL |
| 49152–65535 | Dynamic and/or private ports | **Ephemeral ports** | Temporary client source ports, never assigned to a service |

A server listens on a fixed, well-known port so clients know where to find it. A client doesn't care which port it uses, so the operating system picks a free **ephemeral port** for it every time it opens a connection.

> [!NOTE]
> Operating systems don't all follow the RFC 6335 dynamic range. Windows (since Vista) and macOS use 49152–65535 by default, but Linux uses 32768–60999. Check yours with `cat /proc/sys/net/ipv4/ip_local_port_range` on Linux, `sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last` on macOS, or `netsh int ipv4 show dynamicport tcp` on Windows. This matters when you write firewall rules for return traffic.

A program's endpoint, an IP address plus a port plus a protocol, is called a **socket**. One connection is identified by its **4-tuple**: source IP address, source port, destination IP address, destination port. Add the protocol and you get the **5-tuple** that firewalls and Network Address Translation (NAT) devices track. Because the client's port differs, two browser tabs can talk to the same server port at the same time without mixing their data:

<figure class="diagram" style="--dg-w: 940px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 940 470" width="940" height="470" role="img" aria-labelledby="tcp-ports-sockets-title tcp-ports-sockets-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-ports-sockets-title">Ports identify processes; a 4-tuple identifies a connection</title>
<desc id="tcp-ports-sockets-desc">A client at 192.0.2.10 runs two browser tabs and an SSH client. The operating system gives each one an ephemeral source port: 50514, 50515 and 50600. A server at 203.0.113.80 listens on the well-known ports 443 (web server, HTTPS) and 22 (SSH server). Both browser connections go to port 443 and the SSH connection to port 22. The three TCP connections are told apart by their 4-tuples: 192.0.2.10:50514 to 203.0.113.80:443, 192.0.2.10:50515 to 203.0.113.80:443, and 192.0.2.10:50600 to 203.0.113.80:22.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="939" height="469" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<rect class="dg-card" x="30" y="30" width="300" height="290" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(46 46) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="88" y="67" font-size="15" class="dg-text" fill="#17171c" font-weight="700">Client</text>
<text x="48" y="98" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10</text>
<text x="48" y="128" font-size="11.5" class="dg-muted" fill="#5c5c68" font-weight="600">Ephemeral ports (chosen by the OS)</text>
<text x="48" y="164" font-size="13" class="dg-text" fill="#17171c" font-weight="600">Browser tab 1</text>
<g class="dg-l4"><rect class="dg-solid" x="238" y="146" width="74" height="26" rx="13" fill="#c2410c"/><text x="275" y="163.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">:50514</text></g>
<text x="48" y="224" font-size="13" class="dg-text" fill="#17171c" font-weight="600">Browser tab 2</text>
<g class="dg-l4"><rect class="dg-solid" x="238" y="206" width="74" height="26" rx="13" fill="#c2410c"/><text x="275" y="223.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">:50515</text></g>
<text x="48" y="284" font-size="13" class="dg-text" fill="#17171c" font-weight="600">SSH client</text>
<g class="dg-l4"><rect class="dg-solid" x="238" y="266" width="74" height="26" rx="13" fill="#c2410c"/><text x="275" y="283.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">:50600</text></g>
<rect class="dg-card" x="610" y="30" width="300" height="290" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(626 46) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01"/><path d="M6 18h.01"/></g>
<text x="668" y="67" font-size="15" class="dg-text" fill="#17171c" font-weight="700">Server</text>
<text x="628" y="98" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80</text>
<text x="628" y="128" font-size="11.5" class="dg-muted" fill="#5c5c68" font-weight="600">Listening ports (well known)</text>
<g class="dg-l4"><rect class="dg-tint" x="628" y="176" width="64" height="26" rx="13" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="660" y="193.5" font-size="12" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle">:443</text></g>
<text x="704" y="194" font-size="13" class="dg-text" fill="#17171c" font-weight="600">Web server</text>
<g class="dg-l4"><rect class="dg-tint" x="628" y="266" width="64" height="26" rx="13" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="660" y="283.5" font-size="12" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle">:22</text></g>
<text x="704" y="284" font-size="13" class="dg-text" fill="#17171c" font-weight="600">SSH server</text>
<g class="dg-l4"><path class="dg-stroke" d="M318 159C470 159 470 189 618 189" stroke="#c2410c" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M613 183l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M318 219C470 219 470 189 618 189" stroke="#c2410c" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M613 183l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M318 279C470 279 470 279 618 279" stroke="#c2410c" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M613 273l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<rect class="dg-panel" x="30" y="344" width="880" height="106" rx="12" fill="#f0f0ec"/>
<text x="48" y="370" font-size="12.5" class="dg-text" fill="#17171c" font-weight="700">Each connection is a unique 4-tuple: source IP:port → destination IP:port</text>
<g class="dg-l4"><text x="48" y="396" font-size="12.5" class="dg-ink" fill="#c2410c" font-weight="700" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">TCP</text></g>
<text x="110" y="396" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10:50514</text>
<text x="270" y="396" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="700">→</text>
<text x="300" y="396" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80:443</text>
<g class="dg-l4"><text x="48" y="416" font-size="12.5" class="dg-ink" fill="#c2410c" font-weight="700" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">TCP</text></g>
<text x="110" y="416" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10:50515</text>
<text x="270" y="416" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="700">→</text>
<text x="300" y="416" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80:443</text>
<g class="dg-l4"><text x="48" y="436" font-size="12.5" class="dg-ink" fill="#c2410c" font-weight="700" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">TCP</text></g>
<text x="110" y="436" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10:50600</text>
<text x="270" y="436" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="700">→</text>
<text x="300" y="436" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80:22</text>
</svg></figure>

*Figure 1. Two connections share the destination `203.0.113.80:443`. They are still separate, because their 4-tuples differ in the source port.*

Some ports you will meet constantly:

| Port | Protocol | Service |
|---|---|---|
| 22 | TCP | Secure Shell (SSH) |
| 25 | TCP | Simple Mail Transfer Protocol (SMTP), server to server |
| 53 | UDP and TCP | DNS |
| 67 / 68 | UDP | Dynamic Host Configuration Protocol (DHCP), server / client |
| 80 | TCP | Hypertext Transfer Protocol (HTTP) |
| 123 | UDP | Network Time Protocol (NTP) |
| 443 | TCP, and UDP for HTTP/3 | HTTPS |
| 3389 | TCP and UDP | Remote Desktop Protocol (RDP) |

TCP and UDP have separate port spaces. TCP port 53 and UDP port 53 are two different sockets, and a program can listen on one without the other.

> [!CHECK]
> Your laptop opens two connections to `https://www.example.com` at the same time. Both go to `203.0.113.80:443`. How does the server keep their data apart?
>
> - [ ] Each connection uses a different destination port on the server
> - [x] The laptop uses a different ephemeral source port for each, so the two 4-tuples differ
> - [ ] The server can only handle one connection per client IP address at a time
> - [ ] The browser adds a connection number to the IP header
>
> The server port stays 443 for both. The operating system gives each connection its own ephemeral source port, and the 4-tuple (source IP, source port, destination IP, destination port) identifies each connection uniquely.

### TCP and UDP compared
The Internet has two everyday transport protocols. They make opposite trade-offs.

The **User Datagram Protocol (UDP)** (RFC 768) is the minimal option. It adds an 8-byte header (source port, destination port, length and a checksum) and sends the message. Each message is a **datagram**: it arrives whole or not at all. UDP is **connectionless**: there is no setup, no acknowledgement and no retransmission. If a datagram is lost, duplicated or overtaken by a later one, UDP doesn't notice. The application decides whether that matters.

The **Transmission Control Protocol (TCP)** (RFC 9293) does much more. It is **connection-oriented**: both sides agree to talk before any data flows. It then delivers a reliable, ordered **byte stream**: every byte is numbered, acknowledged and resent if lost, and the receiving program reads the bytes in the order they were sent. TCP also slows down when the receiver or the network can't keep up. Its unit of data is a **segment**, with a header of 20 to 60 bytes.

<figure class="diagram" style="--dg-w: 940px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 940 400" width="940" height="400" role="img" aria-labelledby="tcp-vs-udp-title tcp-vs-udp-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-vs-udp-title">TCP compared with UDP</title>
<desc id="tcp-vs-udp-desc">Side-by-side comparison. Before sending, TCP performs a three-way handshake; UDP just sends. Delivery: TCP acknowledges data and resends losses; UDP is best effort with no acknowledgements. Order: TCP delivers one ordered byte stream; UDP delivers separate datagrams. Flow and congestion control: built into TCP; none in UDP, so it is the application&#x27;s job. Header size: 20 to 60 bytes for TCP, 8 bytes for UDP. Typical TCP uses: HTTPS on port 443, SSH on 22, SMTP on 25, IMAPS on 993. Typical UDP uses: DNS on 53, DHCP on 67 and 68, NTP on 123 and QUIC on 443.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="939" height="399" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<g class="dg-l4"><rect class="dg-tint" x="20" y="20" width="440" height="360" rx="16" fill="#fbf4f0" stroke="#e7b39e" stroke-width="1.2" stroke-dasharray="6 5"/>
<text x="38" y="47" font-size="13" class="dg-ink" fill="#c2410c" font-weight="700">TCP · Transmission Control Protocol</text></g>
<text x="42" y="80" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">BEFORE SENDING</text>
<g class="dg-l4"><text x="42" y="100" font-size="14" class="dg-ink" fill="#c2410c" font-weight="700">Three-way handshake</text></g>
<text x="42" y="126" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">DELIVERY</text>
<g class="dg-l4"><text x="42" y="146" font-size="14" class="dg-ink" fill="#c2410c" font-weight="700">Acknowledged; losses resent</text></g>
<text x="42" y="172" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">ORDER</text>
<g class="dg-l4"><text x="42" y="192" font-size="14" class="dg-ink" fill="#c2410c" font-weight="700">One ordered byte stream</text></g>
<text x="42" y="218" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">FLOW / CONGESTION CONTROL</text>
<g class="dg-l4"><text x="42" y="238" font-size="14" class="dg-ink" fill="#c2410c" font-weight="700">Built in</text></g>
<text x="42" y="264" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">HEADER SIZE</text>
<g class="dg-l4"><text x="42" y="284" font-size="14" class="dg-ink" fill="#c2410c" font-weight="700">20–60 bytes</text></g>
<text x="42" y="316" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">TYPICAL USES</text>
<g class="dg-l4"><rect class="dg-solid" x="42" y="330" width="89" height="26" rx="13" fill="#c2410c"/><text x="86.5" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">HTTPS 443</text></g>
<g class="dg-l4"><rect class="dg-solid" x="137" y="330" width="67" height="26" rx="13" fill="#c2410c"/><text x="170.5" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">SSH 22</text></g>
<g class="dg-l4"><rect class="dg-solid" x="210" y="330" width="74" height="26" rx="13" fill="#c2410c"/><text x="247" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">SMTP 25</text></g>
<g class="dg-l4"><rect class="dg-solid" x="290" y="330" width="89" height="26" rx="13" fill="#c2410c"/><text x="334.5" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">IMAPS 993</text></g>
<g class="dg-l1"><rect class="dg-tint" x="480" y="20" width="440" height="360" rx="16" fill="#f0f6f9" stroke="#9ac3d9" stroke-width="1.2" stroke-dasharray="6 5"/>
<text x="498" y="47" font-size="13" class="dg-ink" fill="#0369a1" font-weight="700">UDP · User Datagram Protocol</text></g>
<text x="502" y="80" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">BEFORE SENDING</text>
<g class="dg-l1"><text x="502" y="100" font-size="14" class="dg-ink" fill="#0369a1" font-weight="700">Nothing: just send</text></g>
<text x="502" y="126" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">DELIVERY</text>
<g class="dg-l1"><text x="502" y="146" font-size="14" class="dg-ink" fill="#0369a1" font-weight="700">Best effort; no ACKs</text></g>
<text x="502" y="172" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">ORDER</text>
<g class="dg-l1"><text x="502" y="192" font-size="14" class="dg-ink" fill="#0369a1" font-weight="700">Separate datagrams</text></g>
<text x="502" y="218" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">FLOW / CONGESTION CONTROL</text>
<g class="dg-l1"><text x="502" y="238" font-size="14" class="dg-ink" fill="#0369a1" font-weight="700">None (application&#x27;s job)</text></g>
<text x="502" y="264" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">HEADER SIZE</text>
<g class="dg-l1"><text x="502" y="284" font-size="14" class="dg-ink" fill="#0369a1" font-weight="700">8 bytes</text></g>
<text x="502" y="316" font-size="10.5" class="dg-muted" fill="#5c5c68" font-weight="700" letter-spacing="1">TYPICAL USES</text>
<g class="dg-l1"><rect class="dg-solid" x="502" y="330" width="67" height="26" rx="13" fill="#0369a1"/><text x="535.5" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">DNS 53</text></g>
<g class="dg-l1"><rect class="dg-solid" x="575" y="330" width="96" height="26" rx="13" fill="#0369a1"/><text x="623" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">DHCP 67/68</text></g>
<g class="dg-l1"><rect class="dg-solid" x="677" y="330" width="74" height="26" rx="13" fill="#0369a1"/><text x="714" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">NTP 123</text></g>
<g class="dg-l1"><rect class="dg-solid" x="757" y="330" width="82" height="26" rx="13" fill="#0369a1"/><text x="798" y="347.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">QUIC 443</text></g>
</svg></figure>

*Figure 2. TCP buys reliability and order with a handshake, acknowledgements and a bigger header. UDP gives you speed and simplicity and leaves the rest to the application.*

Choosing between them is a question of what hurts more: waiting or losing data.

| Application | Usual choice | Why |
|---|---|---|
| Web pages, application programming interfaces (APIs), file transfer, email, SSH | TCP | Every byte must arrive, in order. A short delay is acceptable. |
| DNS queries | UDP (TCP for large answers and zone transfers) | One small question, one small answer. A lost query is simply asked again. RFC 7766 requires DNS servers to support TCP too. |
| Voice and video calls, online games | UDP | A late packet is useless. Better to skip it than to stall everything while it is resent. |
| DHCP | UDP | The client has no IP address yet and must broadcast. TCP can't broadcast: a connection has exactly two ends. |
| Live video to many receivers (multicast) | UDP | Same reason: TCP is one-to-one only. |

UDP isn't "unreliable" in a bad sense. It is *unopinionated*. **QUIC** (RFC 9000) is the best example: it runs on top of UDP and builds its own reliability, ordering, congestion control and built-in Transport Layer Security (TLS) 1.3 encryption. HTTP/3 (RFC 9114) uses QUIC, which is why HTTPS today uses both TCP port 443 and UDP port 443.

> [!CHECK]
> A team builds a multiplayer game. The server sends each player's position 30 times per second. Which transport fits best, and why?
>
> - [ ] TCP, because a lost position update must always be resent
> - [x] UDP, because a resent old position is useless once a newer one exists, and waiting for it would freeze the game
> - [ ] UDP, because it encrypts the data and stops cheating
> - [ ] TCP, because UDP can't carry more than one message per second
>
> Each update replaces the previous one, so a retransmission arrives too late to help, and TCP's in-order delivery would hold back newer updates while it waits. Neither TCP nor UDP encrypts anything by itself.

### The TCP connection: handshake and teardown
A TCP connection starts with the **three-way handshake**. Think of a phone call: "Can you hear me?" "Yes, I can hear you, can you hear me?" "Yes." Only then does the conversation start.

The handshake uses flags, single bits in the TCP header. The **SYN** (synchronize) flag opens a connection, the **ACK** (acknowledgement) flag says the acknowledgement number is valid, the **FIN** (finish) flag closes one direction, and the **RST** (reset) flag aborts a connection at once.

<figure class="diagram" style="--dg-w: 940px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 940 563" width="940" height="563" role="img" aria-labelledby="tcp-handshake-title tcp-handshake-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-handshake-title">TCP three-way handshake and the first data</title>
<desc id="tcp-handshake-desc">The client 192.0.2.10 port 50514 is CLOSED and the server 203.0.113.80 port 443 is in LISTEN. 1. The client sends SYN with sequence number 1000 and enters SYN-SENT; the server enters SYN-RECEIVED. 2. The server answers SYN, ACK with its own sequence number 5000 and acknowledgement 1001; the client becomes ESTABLISHED. 3. The client sends ACK with acknowledgement 5001; the server becomes ESTABLISHED. The client then sends 100 bytes of data starting at sequence number 1001, and the server acknowledges with 1101, the next byte it expects.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="939" height="562" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<path class="dg-line" d="M200 98V547" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<path class="dg-line" d="M740 98V547" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<rect class="dg-card" x="95" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(109 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="147" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Client</text>
<text x="147" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10:50514</text>
<rect class="dg-card" x="635" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(649 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01"/><path d="M6 18h.01"/></g>
<text x="687" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Server</text>
<text x="687" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80:443</text>
<g class="dg-l4"><rect class="dg-tint" x="167.955" y="112" width="64.09" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="127" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">CLOSED</text></g>
<g class="dg-l4"><rect class="dg-tint" x="707.955" y="112" width="64.09" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="127" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">LISTEN</text></g>
<text x="470" y="166" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN  seq=1000</text>
<g class="dg-l4"><circle class="dg-solid" cx="402.438" cy="162" r="11" fill="#c2410c"/><text x="402.438" y="166.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">1</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M204 180H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 174l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="160.94" y="202" width="78.12" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="217" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN-SENT</text></g>
<g class="dg-l4"><rect class="dg-tint" x="686.91" y="202" width="106.18" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="217" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN-RECEIVED</text></g>
<text x="470" y="256" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN, ACK  seq=5000 ack=1001</text>
<g class="dg-l4"><circle class="dg-solid" cx="349.062" cy="252" r="11" fill="#c2410c"/><text x="349.062" y="256.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">2</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M736 270H206" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M214 264l-8 6 8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="150.418" y="292" width="99.165" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="307" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ESTABLISHED</text></g>
<text x="470" y="346" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=5001</text>
<g class="dg-l4"><circle class="dg-solid" cx="402.438" cy="342" r="11" fill="#c2410c"/><text x="402.438" y="346.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">3</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M204 360H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 354l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="690.418" y="382" width="99.165" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="397" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ESTABLISHED</text></g>
<text x="470" y="436" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle">seq=1001, 100 bytes of data</text>
<text x="470" y="453" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" text-anchor="middle">(for example a TLS ClientHello)</text>
<g class="dg-l1"><path class="dg-stroke" d="M204 467H734" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M726 461l8 6-8 6" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="470" y="505" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=1101</text>
<g class="dg-l1"><path class="dg-stroke" d="M736 519H206" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M214 513l-8 6 8 6" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
</svg></figure>

*Figure 3. Three messages open the connection. Each side picks its own starting sequence number and the other side acknowledges it plus one.*

1. **SYN.** The client picks an **initial sequence number (ISN)**, here 1000, and sends a segment with the SYN flag. It also announces options such as its **Maximum Segment Size (MSS)**, the largest chunk of data it can receive in one segment.
2. **SYN, ACK.** The server picks its own ISN (5000) and acknowledges the client's: `ack=1001` means "I got your SYN; the next byte I expect from you is 1001". A SYN counts as one byte of sequence space even though it carries no data.
3. **ACK.** The client acknowledges the server's SYN with `ack=5001`. Both sides are now **ESTABLISHED** and data can flow in both directions.

Real ISNs aren't 1000 and 5000. They are 32-bit numbers chosen unpredictably (RFC 9293, following RFC 6528), so that an attacker can't guess them and inject fake segments into a connection.

Closing is a four-step affair, because each direction closes separately:

<figure class="diagram" style="--dg-w: 940px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 940 685" width="940" height="685" role="img" aria-labelledby="tcp-teardown-title tcp-teardown-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-teardown-title">Closing a TCP connection: FIN, ACK, FIN, ACK</title>
<desc id="tcp-teardown-desc">Both sides start ESTABLISHED. 1. The client closes first and sends FIN with sequence number 1101, entering FIN-WAIT-1. 2. The server acknowledges with 1102 and enters CLOSE-WAIT; the client enters FIN-WAIT-2. When the server application finishes and calls close, 3. the server sends its own FIN with sequence number 5001 and enters LAST-ACK; the client enters TIME-WAIT. 4. The client acknowledges with 5002 and the server goes to CLOSED. The client stays in TIME-WAIT for twice the maximum segment lifetime, 60 seconds on Linux, before it is CLOSED.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="939" height="684" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<path class="dg-line" d="M200 98V669" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<path class="dg-line" d="M740 98V669" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<rect class="dg-card" x="95" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(109 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="147" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Client</text>
<text x="147" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10:50514</text>
<rect class="dg-card" x="635" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(649 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01"/><path d="M6 18h.01"/></g>
<text x="687" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Server</text>
<text x="687" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80:443</text>
<g class="dg-l4"><rect class="dg-tint" x="150.418" y="112" width="99.165" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="127" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ESTABLISHED</text></g>
<g class="dg-l4"><rect class="dg-tint" x="690.418" y="112" width="99.165" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="127" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ESTABLISHED</text></g>
<text x="470" y="166" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">FIN  seq=1101</text>
<g class="dg-l4"><circle class="dg-solid" cx="402.438" cy="162" r="11" fill="#c2410c"/><text x="402.438" y="166.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">1</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M204 180H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 174l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="153.925" y="202" width="92.15" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="217" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">FIN-WAIT-1</text></g>
<text x="470" y="256" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=1102</text>
<g class="dg-l4"><circle class="dg-solid" cx="402.438" cy="252" r="11" fill="#c2410c"/><text x="402.438" y="256.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">2</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M736 270H206" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M214 264l-8 6 8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="153.925" y="292" width="92.15" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="307" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">FIN-WAIT-2</text></g>
<g class="dg-l4"><rect class="dg-tint" x="693.925" y="292" width="92.15" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="307" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">CLOSE-WAIT</text></g>
<g class="dg-l1"><rect class="dg-tint" x="566.5" y="330" width="347" height="31" rx="8" fill="#e6f0f6" stroke="#8ebcd5" stroke-width="1.2"/>
<text x="740" y="347" font-size="12.5" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle">Server application finishes and calls close()</text>
</g>
<text x="470" y="395" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">FIN  seq=5001</text>
<g class="dg-l4"><circle class="dg-solid" cx="402.438" cy="391" r="11" fill="#c2410c"/><text x="402.438" y="395.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">3</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M736 409H206" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M214 403l-8 6 8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="157.433" y="431" width="85.135" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="446" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">TIME-WAIT</text></g>
<g class="dg-l4"><rect class="dg-tint" x="700.94" y="431" width="78.12" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="446" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">LAST-ACK</text></g>
<text x="470" y="485" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=5002</text>
<g class="dg-l4"><circle class="dg-solid" cx="402.438" cy="481" r="11" fill="#c2410c"/><text x="402.438" y="485.5" font-size="12" class="dg-on" fill="#ffffff" font-weight="700" text-anchor="middle">4</text></g>
<g class="dg-l4"><path class="dg-stroke" d="M204 499H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 493l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><rect class="dg-tint" x="707.955" y="521" width="64.09" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="740" y="536" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">CLOSED</text></g>
<g class="dg-l7"><rect class="dg-tint" x="54.5" y="559" width="291" height="48" rx="8" fill="#f0eafb" stroke="#bd9eee" stroke-width="1.2"/>
<text x="200" y="576" font-size="12.5" class="dg-ink" fill="#6d28d9" font-weight="600" text-anchor="middle">TIME-WAIT: waits 2 × MSL, then CLOSED</text>
<text x="200" y="593" font-size="12.5" class="dg-ink" fill="#6d28d9" font-weight="600" text-anchor="middle">(Linux: 60 s)</text>
</g>
<g class="dg-l4"><rect class="dg-tint" x="167.955" y="625" width="64.09" height="22" rx="11" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="200" y="640" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">CLOSED</text></g>
</svg></figure>

*Figure 4. Each side sends its own FIN. The side that closes first ends up in TIME-WAIT; the other side is done as soon as its FIN is acknowledged.*

- The side that closes first sends FIN: "I have nothing more to send." The other side acknowledges it and enters **CLOSE-WAIT**: it may still send data until its own application calls `close()`. This one-way state is a **half-close**.
- When the second side sends its FIN and it is acknowledged, that side is CLOSED.
- The side that closed first waits in **TIME-WAIT** (`TIME_WAIT` in `netstat`) for twice the **Maximum Segment Lifetime (MSL)** before it forgets the connection.

**Why TIME-WAIT exists.** It has two jobs. First, if the very last ACK is lost, the other side will resend its FIN, and someone must still be there to acknowledge it again. Second, it stops delayed segments from the old connection from being accepted by a new connection that happens to reuse the same 4-tuple. RFC 9293 defines MSL as 2 minutes, which would make TIME-WAIT 4 minutes; Linux uses a fixed 60 seconds. TIME-WAIT is normal and costs very little memory. A busy client or proxy that opens many short connections can show thousands of them, and that is not a leak. It becomes a problem only when one client opens so many connections to the *same* server address and port that it runs out of ephemeral ports. The cure is to reuse connections (HTTP keep-alive, connection pools), not to switch TIME-WAIT off.

A connection can also end abruptly with RST: a program crashes, a firewall resets the connection, or a segment arrives for a connection that doesn't exist.

> [!CHECK]
> After a client closes a TCP connection to a web server, `ss` on the client shows the connection in `TIME-WAIT` for about a minute. What does that tell you?
>
> - [ ] The server never answered the client's FIN, so the connection is stuck
> - [ ] The client application forgot to call `close()`
> - [x] Nothing is wrong: the side that closes first waits there so a lost final ACK can be resent and old segments can expire
> - [ ] The client is still sending data to the server
>
> TIME-WAIT is the normal last state for whoever sends the first FIN. An application that forgets to call `close()` shows up as CLOSE-WAIT instead, on its own side.

### Reliability: sequence numbers, acknowledgements and windows
TCP numbers bytes, not segments. The **sequence number** in each segment is the number of its first data byte. The **acknowledgement number** is the next byte the receiver expects, and it is cumulative: `ack=4001` means "I have everything up to byte 4000". In Figure 3, the client sends 100 bytes starting at 1001, so the server answers `ack=1101`.

The sender keeps every byte until it is acknowledged. If an acknowledgement doesn't arrive in time, the **retransmission timeout (RTO)** expires and the sender resends. The timeout adapts to the measured round-trip time (RFC 6298). There is a faster signal too: if the receiver gets a segment out of order, it repeats its last acknowledgement. Three of these **duplicate ACKs** in a row tell the sender that a segment is missing, and it resends at once without waiting for the timer. This is **fast retransmit** (RFC 5681).

<figure class="diagram" style="--dg-w: 940px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 940 581" width="940" height="581" role="img" aria-labelledby="tcp-retransmission-title tcp-retransmission-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-retransmission-title">TCP retransmission after a lost segment</title>
<desc id="tcp-retransmission-desc">The sender 192.0.2.10 sends 1000 bytes at sequence number 1001; the receiver 203.0.113.80 acknowledges 2001 and advertises a receive window of 64000 bytes. The next segment, at 2001, is lost in the network. The segment at 3001 arrives, but the receiver can only acknowledge 2001 again, a duplicate acknowledgement. Duplicate acknowledgements or the retransmission timer make the sender resend the segment at 2001. The receiver now has everything up to byte 4000 and acknowledges 4001.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="939" height="580" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<path class="dg-line" d="M200 98V565" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<path class="dg-line" d="M740 98V565" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<rect class="dg-card" x="95" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(109 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="147" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Sender</text>
<text x="147" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10</text>
<rect class="dg-card" x="635" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(649 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01"/><path d="M6 18h.01"/></g>
<text x="687" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Receiver</text>
<text x="687" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">203.0.113.80</text>
<text x="470" y="128" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">seq=1001, 1000 bytes</text>
<g class="dg-l4"><path class="dg-stroke" d="M204 142H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 136l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="470" y="180" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=2001  win=64000</text>
<g class="dg-l1"><path class="dg-stroke" d="M736 194H206" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M214 188l-8 6 8 6" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="470" y="232" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">seq=2001, 1000 bytes</text>
<g class="dg-l4"><path class="dg-stroke" d="M204 246H524.8" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M527.8 239l14 14m0-14l-14 14" stroke="#b91c1c" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="470" y="284" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">seq=3001, 1000 bytes</text>
<g class="dg-l4"><path class="dg-stroke" d="M204 298H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 292l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="470" y="336" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=2001</text>
<text x="470" y="353" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">(duplicate: &quot;still missing byte 2001&quot;)</text>
<g class="dg-warn"><path class="dg-stroke" d="M736 367H206" stroke="#b91c1c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M214 361l-8 6 8 6" stroke="#b91c1c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l7"><rect class="dg-tint" x="47.5" y="389" width="305" height="48" rx="8" fill="#f0eafb" stroke="#bd9eee" stroke-width="1.2"/>
<text x="200" y="406" font-size="12.5" class="dg-ink" fill="#6d28d9" font-weight="600" text-anchor="middle">Duplicate ACKs or retransmission timer:</text>
<text x="200" y="423" font-size="12.5" class="dg-ink" fill="#6d28d9" font-weight="600" text-anchor="middle">resend the missing segment</text>
</g>
<text x="470" y="471" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">seq=2001, 1000 bytes (retransmitted)</text>
<g class="dg-l4"><path class="dg-stroke" d="M204 485H734" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M726 479l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="470" y="523" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ACK  ack=4001</text>
<g class="dg-l1"><path class="dg-stroke" d="M736 537H206" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M214 531l-8 6 8 6" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
</svg></figure>

*Figure 5. The receiver can only acknowledge up to the first gap. When the gap is filled, one ACK covers both segments.*

Modern TCP also uses **Selective Acknowledgement (SACK)** (RFC 2018), so the receiver can say exactly which blocks it already has and the sender resends only what is missing.

Two more mechanisms stop TCP from sending too fast:
- **Flow control** protects the *receiver*. Every segment carries a **receive window** (`win`): how many more bytes the receiver can buffer right now. The sender never has more unacknowledged data in flight than that. If the window drops to 0, the sender stops and waits. Window scaling (RFC 7323) lets the window grow beyond 64 KB for fast links.
- **Congestion control** protects the *network*. The sender keeps its own estimate, the congestion window, and starts small (slow start), grows while acknowledgements come back, and backs off when it sees loss (RFC 5681). Linux uses the CUBIC algorithm by default (RFC 9438); BBR, developed by Google, is a common alternative.

UDP has none of this. An application on UDP that needs reliability or rate control, like QUIC, must build it.

> [!CHECK]
> A receiver advertises `win=0` in its acknowledgements. What does the sender do?
>
> - [ ] Resends all unacknowledged data immediately
> - [ ] Closes the connection with FIN
> - [x] Stops sending new data until the receiver advertises a window larger than 0
> - [ ] Switches the connection to UDP
>
> A zero receive window is flow control: the receiving application isn't reading fast enough and its buffer is full. The sender pauses and periodically probes until the window opens again.

### Sockets and their states
On any host you can list the sockets the operating system has open. On Linux the tool is `ss` (socket statistics); on macOS and Windows, `netstat`.

| State (as `ss` shows it) | Meaning | Typical cause |
|---|---|---|
| `LISTEN` | A server socket waiting for connections | A service is running and accepts connections on that address and port |
| `SYN-SENT` | A connect is in progress; no answer yet | Many of them: the destination doesn't answer (look for a timeout) |
| `SYN-RECV` | A SYN arrived and the SYN, ACK was sent | Many of them: a slow network or a SYN flood |
| `ESTAB` | An established connection | Normal traffic |
| `CLOSE-WAIT` | The peer closed; our application hasn't yet | Many of them: an application bug (it never calls `close()`) |
| `TIME-WAIT` | We closed first and are waiting 2 × MSL | Normal; many of them on busy clients and proxies |
| `UNCONN` | A UDP socket (UDP has no connections) | A UDP service such as DNS or NTP |

`netstat` and the RFC spell the states slightly differently: `ESTABLISHED`, `TIME_WAIT`, `CLOSE_WAIT` and, on Windows, `LISTENING`. They mean the same thing.

A **listening socket** is bound to an address as well as a port, and that address decides who can connect:
- `127.0.0.1:5432` (or `[::1]:5432`): only programs on the same machine, through the loopback interface.
- `0.0.0.0:22` (or `[::]:22`, or `*:22`): every IPv4 (or IPv6) address the host has, so anyone who can reach the host.
- `203.0.113.80:443`: only connections that arrive for that one address.

A server that "works locally but not from outside" is very often listening on `127.0.0.1` only.

The commands you need most:

| Task | Linux | macOS | Windows (PowerShell) |
|---|---|---|---|
| Listening TCP and UDP sockets, with the program | `ss -tulpn` | `lsof -nP -iTCP -sTCP:LISTEN` and `lsof -nP -iUDP` | `netstat -ano` or `Get-NetTCPConnection -State Listen` |
| All TCP sockets with their state | `ss -tan` | `netstat -an -p tcp` | `netstat -an -p tcp` |

In `ss -tulpn`, the letters mean: `-t` TCP, `-u` UDP, `-l` listening sockets only, `-p` show the process, `-n` show numbers instead of service names. On Linux you only see the process of sockets owned by other users if you run it with `sudo`.

To count TCP sockets per state, which quickly shows a pile-up of TIME-WAIT or CLOSE-WAIT, on Linux:

```bash
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c
```

On Windows (PowerShell), `Get-NetTCPConnection | Group-Object State` does the same.

> [!CHECK]
> `ss -tln` on a server shows `LISTEN 0 4096 127.0.0.1:8000 0.0.0.0:*`. Your colleague can't reach port 8000 from their laptop. What is the most likely reason?
>
> - [ ] The port is above 1023, so only administrators can connect to it
> - [ ] The service is in TIME-WAIT and will accept connections in a minute
> - [x] The service listens on the loopback address only, so it accepts connections from the server itself and nowhere else
> - [ ] `0.0.0.0:*` means every client is blocked
>
> The local address `127.0.0.1` restricts the listener to the loopback interface. The peer column `0.0.0.0:*` simply means "any peer" for a listening socket. Binding to `0.0.0.0` (and opening the firewall) would make it reachable from outside.

### "Connection refused" versus "connection timed out"
When a TCP connection fails, the error message tells you *how far the SYN got*.

<figure class="diagram" style="--dg-w: 1020px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 1020 405" width="1020" height="405" role="img" aria-labelledby="tcp-refused-vs-timeout-title tcp-refused-vs-timeout-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-refused-vs-timeout-title">Connection refused versus connection timed out</title>
<desc id="tcp-refused-vs-timeout-desc">Left: a client sends SYN to 198.51.100.20 port 8080, where the host is up but nothing listens. The host answers immediately with RST, ACK, and the client reports connection refused within milliseconds. Right: a client sends SYN to 198.51.100.30 port 8080, where a firewall silently drops it. No answer comes back; the client retries the SYN several times and reports connection timed out when its timeout expires.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="1019" height="404" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<path class="dg-line" d="M125 98V288" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<path class="dg-line" d="M380 98V288" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<rect class="dg-card" x="20" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(34 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="72" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Client</text>
<text x="72" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10</text>
<rect class="dg-card" x="275" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(289 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01"/><path d="M6 18h.01"/></g>
<text x="327" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Port closed</text>
<text x="327" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">198.51.100.20:8080</text>
<text x="252.5" y="128" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN</text>
<g class="dg-l4"><path class="dg-stroke" d="M129 142H374" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M366 136l8 6-8 6" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="252.5" y="180" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">RST, ACK</text>
<g class="dg-warn"><path class="dg-stroke" d="M376 194H131" stroke="#b91c1c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M139 188l-8 6 8 6" stroke="#b91c1c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><rect class="dg-tint" x="85" y="216" width="335" height="48" rx="8" fill="#f8e8e8" stroke="#e09999" stroke-width="1.2"/>
<text x="252.5" y="233" font-size="12.5" class="dg-ink" fill="#b91c1c" font-weight="600" text-anchor="middle">Connection refused</text>
<text x="252.5" y="250" font-size="12.5" class="dg-ink" fill="#b91c1c" font-weight="600" text-anchor="middle">(answer in milliseconds)</text>
</g>
<path class="dg-line" d="M640 98V389" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<path class="dg-line" d="M895 98V389" stroke="#cfcfc8" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
<rect class="dg-card" x="535" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(549 38) scale(1.1667)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></g>
<text x="587" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Client</text>
<text x="587" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">192.0.2.10</text>
<rect class="dg-card" x="790" y="24" width="210" height="74" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-warn"><g class="dg-icon" transform="translate(804 38) scale(1.1667)" fill="none" stroke="#b91c1c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/></g></g>
<text x="842" y="56" font-size="14" class="dg-text" fill="#17171c" font-weight="700">Port filtered</text>
<text x="842" y="76" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">198.51.100.30:8080</text>
<text x="767.5" y="128" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN</text>
<g class="dg-l4"><path class="dg-stroke" d="M644 142H788.1" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M791.1 135l14 14m0-14l-14 14" stroke="#b91c1c" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><rect class="dg-tint" x="788" y="164" width="214" height="31" rx="8" fill="#e6f0f6" stroke="#8ebcd5" stroke-width="1.2"/>
<text x="895" y="181" font-size="12.5" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle">Firewall drops it silently</text>
</g>
<text x="767.5" y="229" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN (retry)</text>
<g class="dg-l4"><path class="dg-stroke" d="M644 243H788.1" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M791.1 236l14 14m0-14l-14 14" stroke="#b91c1c" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<text x="767.5" y="281" font-size="12.5" class="dg-text" fill="#17171c" font-weight="600" text-anchor="middle" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">SYN (retry)</text>
<g class="dg-l4"><path class="dg-stroke" d="M644 295H788.1" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M791.1 288l14 14m0-14l-14 14" stroke="#b91c1c" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><rect class="dg-tint" x="600" y="317" width="335" height="48" rx="8" fill="#f8e8e8" stroke="#e09999" stroke-width="1.2"/>
<text x="767.5" y="334" font-size="12.5" class="dg-ink" fill="#b91c1c" font-weight="600" text-anchor="middle">Connection timed out</text>
<text x="767.5" y="351" font-size="12.5" class="dg-ink" fill="#b91c1c" font-weight="600" text-anchor="middle">(after the timeout expires)</text>
</g>
<path class="dg-line" d="M510 30V385" stroke="#cfcfc8" stroke-width="1" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="7 6"/>
</svg></figure>

*Figure 6. Refused means something answered. Timed out means nothing did.*

- **Connection refused** (`ECONNREFUSED`). The SYN reached the destination host, but no program is listening on that port, so the host's TCP stack answered with RST. You get the error almost instantly. A firewall configured to *reject* instead of *drop* has the same effect, by sending RST or an Internet Control Message Protocol (ICMP) "port unreachable" message. Look at the server: is the service running? Is it listening on the right port and address (`ss -tlnp`)?
- **Connection timed out** (`ETIMEDOUT`). No answer came back at all. The client resends the SYN several times, waiting longer each time, and gives up when its timeout expires. Causes: a firewall or cloud security group that silently drops the traffic, a host that is switched off, a wrong IP address, or a routing problem. Look at the path: firewalls, security groups, routes.

How long "timed out" takes depends on the client. On Linux with default settings, the kernel retries the SYN with gaps that start at about 1 second and then double, and gives up after a little over 2 minutes (we measured 136 s on Linux 7.2 with `net.ipv4.tcp_syn_retries = 6`). Most applications set their own shorter limit, for example `curl --connect-timeout 5`.

Two related errors come from the network layer rather than from the target:
- **No route to host** (`EHOSTUNREACH`): a router sent back an ICMP "host unreachable", or your own host couldn't resolve the next hop's Media Access Control (MAC) address on the local link.
- **Network is unreachable** (`ENETUNREACH`): your own host has no route to that destination at all (check `ip route`).

UDP has no handshake, so there is nothing to refuse. If a UDP datagram reaches a closed port, the host usually answers with ICMP "port unreachable", and a program that used `connect()` on its UDP socket may see a "connection refused" error on its next receive. More often, a UDP client just hears nothing and has to rely on its own timeout.

> [!NOTE]
> On Windows, a client that receives RST may retry the connection a couple of times before reporting the error, so "refused" can take around two seconds there instead of milliseconds. The distinction (fast answer versus no answer) still holds.

> [!CHECK]
> `curl https://198.51.100.20:8443` fails after exactly 5 seconds with "Connection timed out", using `--connect-timeout 5`. Where do you look first?
>
> - [ ] At the web server's configuration, because it is listening on the wrong port
> - [x] At the path: a firewall, security group or routing problem is dropping the SYN, or the host is down
> - [ ] At the client's ephemeral port range, because it has run out of ports
> - [ ] At TIME-WAIT on the server, because old connections block new ones
>
> A wrong port on a reachable host gives an immediate "connection refused" (RST). A timeout means no answer at all, which points at something dropping packets or at an unreachable host.

## How it works
Put everything together. You type `https://www.example.com` into a browser on a laptop at `192.0.2.10`. The page is served from `203.0.113.80`.

1. **DNS over UDP.** The browser needs the IP address. The laptop sends a DNS query in one UDP datagram from an ephemeral port (say 41837) to the resolver's port 53, and gets one datagram back: `www.example.com` is `203.0.113.80`. No handshake, two packets.
2. **Pick a source port.** The browser asks the operating system for a TCP connection to `203.0.113.80:443`. The operating system picks a free ephemeral port, 50514. The 4-tuple `192.0.2.10:50514 → 203.0.113.80:443` now names this connection.
3. **Three-way handshake.** SYN, SYN-ACK, ACK (Figure 3). It costs one round trip before any data can flow. The server's socket in LISTEN stays open for the next client; the operating system creates a new ESTABLISHED socket for this one.
4. **Data.** The browser starts the TLS handshake, then sends the HTTP request. Every segment carries sequence and acknowledgement numbers; lost segments are retransmitted (Figure 5); the receive window and the congestion window limit how fast data flows.
5. **Teardown.** When the browser is done (often after keeping the connection open for a while for more requests), one side sends FIN, the other answers with ACK and its own FIN (Figure 4). Whoever sent the first FIN keeps the 4-tuple in TIME-WAIT for 60 seconds on Linux.
6. **If something fails** at step 3, the error tells you where: RST means the host is reachable but nothing listens on 443 (refused); silence means something on the path drops the SYN (timed out).

If the browser and server support HTTP/3, steps 2 to 5 run over QUIC on UDP port 443 instead, and QUIC combines its own handshake with the TLS handshake to save a round trip.

> [!CHECK]
> In the sequence above, which messages travel **before** the first byte of the HTTP request leaves the laptop?
>
> - [ ] Only the HTTP request itself; TCP sends data straight away
> - [ ] A UDP handshake with the DNS resolver, then the HTTP request
> - [x] A DNS query and answer over UDP, the TCP three-way handshake, and the TLS handshake
> - [ ] The TCP teardown of the previous connection
>
> DNS needs no handshake, but TCP does (SYN, SYN-ACK, ACK), and HTTPS adds the TLS handshake on top. That is why connection reuse and HTTP/3's combined handshake make pages load faster.

## Worked example
You are asked to check a Linux web server at `203.0.113.80`. All addresses are documentation addresses (RFC 5737).

**Which services are listening?** Run as administrator so `ss` can show every process:

```bash
sudo ss -tulpn
```

```text
Netid State  Recv-Q Send-Q  Local Address:Port  Peer Address:Port Process
udp   UNCONN 0      0           127.0.0.1:323        0.0.0.0:*     users:(("chronyd",pid=702,fd=5))
tcp   LISTEN 0      128           0.0.0.0:22         0.0.0.0:*     users:(("sshd",pid=812,fd=3))
tcp   LISTEN 0      511           0.0.0.0:443        0.0.0.0:*     users:(("nginx",pid=1034,fd=6))
tcp   LISTEN 0      4096        127.0.0.1:5432       0.0.0.0:*     users:(("postgres",pid=990,fd=7))
tcp   LISTEN 0      128              [::]:22            [::]:*     users:(("sshd",pid=812,fd=4))
```

Read it line by line:
- `udp UNCONN 127.0.0.1:323`: the NTP daemon `chronyd` has a UDP socket for local control commands. UDP sockets show `UNCONN` because UDP has no connections.
- `tcp LISTEN 0.0.0.0:22` and `[::]:22`: SSH accepts connections on every IPv4 and IPv6 address.
- `tcp LISTEN 0.0.0.0:443`: the web server, reachable from anywhere the firewall allows.
- `tcp LISTEN 127.0.0.1:5432`: the PostgreSQL database accepts local connections only. That is good: the web application on the same host can use it, the Internet can't.
- For a listening socket, `Send-Q` shows the **backlog**: the maximum number of connections that have completed the handshake but haven't yet been picked up by the program (511 for nginx).

**What connections exist right now?**

```bash
ss -tan
```

```text
State      Recv-Q Send-Q     Local Address:Port      Peer Address:Port
LISTEN     0      128              0.0.0.0:22             0.0.0.0:*
LISTEN     0      511              0.0.0.0:443            0.0.0.0:*
LISTEN     0      4096           127.0.0.1:5432           0.0.0.0:*
ESTAB      0      0           203.0.113.80:443       192.0.2.10:50514
ESTAB      0      36          203.0.113.80:22      198.51.100.7:51022
TIME-WAIT  0      0           203.0.113.80:443       192.0.2.10:50388
ESTAB      0      0              127.0.0.1:5432         127.0.0.1:41870
ESTAB      0      0              127.0.0.1:41870        127.0.0.1:5432
LISTEN     0      128                 [::]:22                [::]:*
```

- `192.0.2.10:50514` is a browser connected to the web server. Its source port is ephemeral; the server side is 443.
- An administrator at `198.51.100.7` is logged in with SSH. `Send-Q 36` means 36 bytes are sent but not yet acknowledged: normal for an active session.
- `TIME-WAIT … 192.0.2.10:50388` is an older connection from the same browser. The *server* closed it first (for example an idle keep-alive timeout), so the server holds the TIME-WAIT.
- The two `127.0.0.1` lines are *one* connection seen from both ends: the web application (port 41870) talking to the database (5432). Loopback connections always appear twice.

**What does a handshake look like on the wire?** A capture with `tcpdump` on the server (`-n` shows numbers, `-t` hides timestamps) shows the start of the browser's connection:

```bash
sudo tcpdump -n -t -i eth0 'tcp port 443 and host 192.0.2.10'
```

```text
IP 192.0.2.10.50514 > 203.0.113.80.443: Flags [S], seq 2864127401, win 64240, options [mss 1460,sackOK,TS val 3017325814 ecr 0,nop,wscale 7], length 0
IP 203.0.113.80.443 > 192.0.2.10.50514: Flags [S.], seq 1207650562, ack 2864127402, win 65160, options [mss 1460,sackOK,TS val 1554302991 ecr 3017325814,nop,wscale 7], length 0
IP 192.0.2.10.50514 > 203.0.113.80.443: Flags [.], ack 1, win 502, options [nop,nop,TS val 3017325839 ecr 1554302991], length 0
IP 192.0.2.10.50514 > 203.0.113.80.443: Flags [P.], seq 1:518, ack 1, win 502, options [nop,nop,TS val 3017325840 ecr 1554302991], length 517
IP 203.0.113.80.443 > 192.0.2.10.50514: Flags [.], ack 518, win 507, options [nop,nop,TS val 1554303016 ecr 3017325840], length 0
```

- `[S]` is SYN, `[S.]` is SYN-ACK (`.` stands for the ACK flag), `[.]` is a bare ACK and `[P.]` is data with the PSH (push) flag. `[F.]` and `[R]` would be FIN and RST.
- The ISNs are random 32-bit numbers: 2864127401 and 1207650562. The SYN-ACK acknowledges 2864127401 + 1.
- From the third line on, `tcpdump` shows *relative* sequence numbers to save space: `ack 1` means "ISN + 1". The client then sends bytes 1 to 517 (`seq 1:518`, `length 517`, a TLS ClientHello) and the server acknowledges 518.
- `mss 1460` is the largest segment each side accepts: a 1500-byte Ethernet frame minus 20 bytes of IP header and 20 of TCP header. `win 502` with `wscale 7` means a receive window of 502 × 2⁷ = 64,256 bytes.

> [!NOTE]
> Window sizes, options and the exact `ss` column layout vary with the operating system version and its settings. The structure (flags, sequence and acknowledgement numbers, states) is the same everywhere. You'll produce your own capture in the lab.

## Common pitfalls
- **Treating "refused" and "timed out" as the same problem.** Refused: go to the server and check the service. Timed out: check firewalls, security groups and routing. Debugging the application when a firewall drops the SYN wastes hours.
- **Binding a service to `127.0.0.1` and wondering why nobody can reach it**, or the opposite: binding a database or admin interface to `0.0.0.0` "to make it work", and exposing it to the Internet.
- **Opening only the server port in a stateless firewall.** Replies go back to the client's ephemeral port. Stateful firewalls handle this automatically; stateless ones (such as some cloud network access control lists, ACLs) need the ephemeral range open for return traffic, and Linux, Windows and macOS use different ranges.
- **"Fixing" TIME-WAIT with kernel tweaks.** Thousands of TIME-WAIT sockets are normal on busy hosts. Reuse connections instead. The old Linux setting `tcp_tw_recycle` broke clients behind NAT and was removed in Linux 4.12.
- **Ignoring CLOSE-WAIT.** CLOSE-WAIT sockets that pile up and never disappear are an application bug: the program never closes connections the peer has already closed. Restarting hides it; fixing the code cures it.
- **Assuming TCP preserves message boundaries.** TCP is a byte stream. Two `send()` calls of 100 bytes may arrive as one read of 200 bytes, or as 150 + 50. Applications must frame their messages (length prefixes, delimiters).
- **Assuming UDP datagrams arrive.** UDP gives no warning when a datagram is lost. An application on UDP needs its own timeouts and retries.
- **Forgetting that TCP and UDP ports are separate.** Allowing TCP port 53 in a firewall doesn't allow DNS over UDP port 53, and vice versa.

## Security considerations
- **SYN floods.** During the handshake, the server keeps a half-open connection (SYN-RECV) for every SYN it answers. An attacker who sends huge numbers of SYNs, usually with spoofed source addresses, can fill that queue so real clients can't connect. The standard defence is **SYN cookies** (RFC 4987): when the queue is full, the server encodes the connection details in its own ISN and keeps no state until a valid ACK comes back. Linux enables them by default (`net.ipv4.tcp_syncookies = 1`). Large attacks also need rate limiting or an upstream mitigation service.
- **Port scanning.** Because closed ports answer with RST, open ports with SYN-ACK and filtered ports with silence, anyone can map which services a host exposes. This is **port scanning**, the same refused-versus-timeout logic you just learned. Defenders scan their *own* networks to find services that shouldn't be exposed. Scanning systems you don't own or aren't explicitly authorized to test may be illegal and violates most providers' terms of service.
- **Expose as little as possible.** Every listening port is attack surface. Bind internal services (databases, caches, admin panels) to `127.0.0.1` or a private address, put a default-deny firewall in front of everything else, and never publish SSH (22), RDP (3389) or databases (3306, 5432, 6379…) directly to the Internet. Use a virtual private network (VPN) or a bastion host instead. Review `ss -tulpn` output regularly.
- **Drop or reject?** Dropping makes scans slower and reveals less; rejecting makes failures fast and clear for legitimate users. Many organizations drop at the Internet edge and reject inside the network.
- **UDP reflection and amplification.** UDP has no handshake, so the source address is easy to forge. Attackers send small queries to open DNS, NTP or memcached servers with the victim's address as the source, and the larger answers flood the victim. Don't run open resolvers or services on UDP that answer anyone, and filter spoofed sources at the network edge (Best Current Practice BCP 38, RFC 2827).
- **TCP and UDP don't encrypt.** Anyone on the path can read and change the data. Use TLS (HTTPS, SMTP with STARTTLS, the Internet Message Access Protocol over TLS, IMAPS), SSH or QUIC for anything sensitive. Unpredictable ISNs (RFC 6528) and the checks in RFC 5961 make blind injection of fake segments or RSTs hard, but they don't protect an attacker who can see the traffic.

## Summary
- The transport layer delivers data to processes. Ports (0–65535) identify them: well-known/system 0–1023, registered/user 1024–49151, dynamic/ephemeral 49152–65535 (RFC 6335). Linux uses 32768–60999 for ephemeral ports by default. A 4-tuple identifies one connection.
- UDP (RFC 768) is connectionless, best effort and minimal: an 8-byte header, separate datagrams, no acknowledgements. TCP (RFC 9293) is connection-oriented, reliable and ordered, with flow and congestion control. QUIC (RFC 9000) builds TCP-like features plus encryption on top of UDP.
- TCP opens with SYN, SYN-ACK, ACK and closes with a FIN and an ACK in each direction. The side that closes first waits in TIME-WAIT (2 × MSL; 60 s on Linux), which is normal.
- Sequence numbers count bytes; acknowledgements name the next byte expected. Lost data is resent after a timeout or duplicate ACKs; the receive window (flow control) and the congestion window limit the sending rate.
- `ss -tulpn` / `ss -tan` (Linux) and `netstat`, `lsof` or `Get-NetTCPConnection` (macOS, Windows) show listening sockets and states. Check the listening address as well as the port.
- "Connection refused" means the host answered with RST: nothing listens there. "Connection timed out" means no answer at all: look at firewalls, routing and whether the host is up.

## Glossary
| Term | Definition |
|---|---|
| Transport layer | OSI Layer 4: carries data between processes on different hosts, using ports. |
| Port | A 16-bit number (0–65535) that identifies a process's endpoint for TCP or UDP on a host. |
| Demultiplexing | Delivering incoming data to the right process according to its destination port. |
| Multiplexing | Combining many processes' data onto one network connection or IP address, labelled with ports. |
| Well-known ports | Ports 0–1023, called system ports in RFC 6335; used by standard services. |
| Registered ports | Ports 1024–49151, called user ports in RFC 6335; assigned to services by IANA on request. |
| Ephemeral port | A temporary port the operating system gives a client for one connection; RFC 6335 reserves 49152–65535 for them. |
| Socket | A communication endpoint: an IP address, a port and a protocol, as used by a program. |
| 4-tuple | Source IP address, source port, destination IP address and destination port: together they identify one connection. |
| 5-tuple | The 4-tuple plus the protocol (TCP or UDP); used by firewalls and NAT. |
| User Datagram Protocol (UDP) | A connectionless, best-effort transport protocol with an 8-byte header (RFC 768). |
| Datagram | A self-contained UDP message that arrives whole or not at all. |
| Connectionless | Sending data without first setting up a connection or keeping state about the peer. |
| Transmission Control Protocol (TCP) | A connection-oriented transport protocol that delivers a reliable, ordered byte stream (RFC 9293). |
| Connection-oriented | Requiring both ends to set up a connection before data is exchanged. |
| Byte stream | TCP's service model: an ordered sequence of bytes with no message boundaries. |
| Segment | The unit of data TCP sends: a TCP header plus a chunk of the byte stream. |
| QUIC | A transport protocol on top of UDP with built-in reliability, streams, congestion control and TLS 1.3 encryption (RFC 9000); used by HTTP/3. |
| Three-way handshake | The SYN, SYN-ACK, ACK exchange that opens a TCP connection. |
| SYN | TCP flag that opens a connection and carries the initial sequence number. |
| ACK | TCP flag that marks the acknowledgement number as valid; set on almost every segment after the first. |
| FIN | TCP flag meaning "I have no more data to send"; closes one direction of a connection. |
| RST | TCP flag that aborts a connection immediately, or refuses a connection to a closed port. |
| Initial sequence number (ISN) | The unpredictable 32-bit starting sequence number each side picks for a connection. |
| Maximum Segment Size (MSS) | The largest amount of data a host accepts in one TCP segment, announced in the SYN. |
| ESTABLISHED | TCP state of an open connection that can carry data (`ESTAB` in `ss`). |
| CLOSE-WAIT | TCP state after the peer has closed but the local application hasn't yet (`CLOSE_WAIT` in `netstat`). |
| Half-close | A TCP connection in which one direction is closed while the other can still send. |
| TIME-WAIT | TCP state of the side that closed first, kept for 2 × MSL (`TIME_WAIT` in `netstat`). |
| Maximum Segment Lifetime (MSL) | The assumed maximum time a segment can survive in the network; 2 minutes in RFC 9293. |
| Sequence number | The number of the first data byte in a TCP segment. |
| Acknowledgement number | The next byte a TCP receiver expects; it acknowledges everything before it. |
| Retransmission timeout (RTO) | The adaptive timer after which TCP resends unacknowledged data (RFC 6298). |
| Duplicate ACK | A repeated acknowledgement for the same byte, sent when a segment arrives out of order. |
| Fast retransmit | Resending a segment after three duplicate ACKs, without waiting for the RTO (RFC 5681). |
| Selective Acknowledgement (SACK) | A TCP option that lets the receiver report exactly which blocks it has received (RFC 2018). |
| Flow control | Limiting the sender to what the receiver can buffer, using the receive window. |
| Receive window | The number of bytes a TCP receiver can still accept, advertised in every segment (`win`). |
| Congestion control | Limiting the sending rate to what the network can carry, using the congestion window (RFC 5681). |
| Listening socket | A server socket in the LISTEN state, waiting for connections on an address and port. |
| Connection refused | Error when the destination answers a SYN with RST (or ICMP port unreachable): nothing is listening. |
| Connection timed out | Error when no answer to the SYN arrives before the client's timeout. |
| No route to host | Error (`EHOSTUNREACH`) when a router reports the host unreachable, or the next hop's MAC address can't be resolved. |
| Network is unreachable | Error (`ENETUNREACH`) when the local host has no route to the destination. |
| Backlog | The queue of connections that have completed the handshake but haven't yet been accepted by the program. |
| SYN cookies | A SYN flood defence that encodes connection state in the server's ISN instead of storing it (RFC 4987). |
| Port scanning | Probing a host's ports to find which ones are open, closed or filtered. |

## Check your understanding
1. Why does a client use an ephemeral port instead of a fixed one, while a server uses a fixed, well-known port?
2. DNS normally uses UDP, but DHCP *must* use UDP. What is the difference in the reasons?
3. In a capture, a SYN has `seq 2000` and the SYN-ACK has `seq 7000`. What acknowledgement numbers do the SYN-ACK and the final ACK carry, and why "plus one"?
4. A server shows 3,000 sockets in `TIME-WAIT` and 2,000 in `CLOSE-WAIT`. Which number would worry you, and what would you look at?
5. `ss -tln` shows your service on `0.0.0.0:8080`, but clients from the Internet get "connection timed out". List two possible causes and how you'd check each.
6. Why are SYN floods a problem for TCP servers, and why don't SYN cookies need the server to remember anything about half-open connections?

## References
- [RFC 9293](https://www.rfc-editor.org/rfc/rfc9293) — Transmission Control Protocol (TCP).
- [RFC 768](https://www.rfc-editor.org/rfc/rfc768) — User Datagram Protocol.
- [RFC 6335](https://www.rfc-editor.org/rfc/rfc6335) — Procedures for the Management of the Service Name and Transport Protocol Port Number Registry.
- [IANA Service Name and Transport Protocol Port Number Registry](https://www.iana.org/assignments/service-names-port-numbers/).
- [RFC 6298](https://www.rfc-editor.org/rfc/rfc6298) — Computing TCP's Retransmission Timer.
- [RFC 5681](https://www.rfc-editor.org/rfc/rfc5681) — TCP Congestion Control.
- [RFC 2018](https://www.rfc-editor.org/rfc/rfc2018) — TCP Selective Acknowledgment Options.
- [RFC 7323](https://www.rfc-editor.org/rfc/rfc7323) — TCP Extensions for High Performance (window scaling, timestamps).
- [RFC 9438](https://www.rfc-editor.org/rfc/rfc9438) — CUBIC for Fast and Long-Distance Networks.
- [RFC 6528](https://www.rfc-editor.org/rfc/rfc6528) — Defending against Sequence Number Attacks.
- [RFC 5961](https://www.rfc-editor.org/rfc/rfc5961) — Improving TCP's Robustness to Blind In-Window Attacks.
- [RFC 4987](https://www.rfc-editor.org/rfc/rfc4987) — TCP SYN Flooding Attacks and Common Mitigations.
- [RFC 7766](https://www.rfc-editor.org/rfc/rfc7766) — DNS Transport over TCP — Implementation Requirements.
- [RFC 9000](https://www.rfc-editor.org/rfc/rfc9000) — QUIC: A UDP-Based Multiplexed and Secure Transport.
- [RFC 9114](https://www.rfc-editor.org/rfc/rfc9114) — HTTP/3.
- [RFC 2827](https://www.rfc-editor.org/rfc/rfc2827) — Network Ingress Filtering (BCP 38).
- [RFC 5737](https://www.rfc-editor.org/rfc/rfc5737) — IPv4 Address Blocks Reserved for Documentation.
- [Linux kernel documentation: IP sysctl](https://docs.kernel.org/networking/ip-sysctl.html) — `ip_local_port_range`, `tcp_syn_retries`, `tcp_syncookies` and related settings.