---
title: "Transport Layer: TCP, UDP and Ports"
domain: networking
level: beginner
duration: "50 min"
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".
---

# Transport Layer: TCP, UDP and Ports

## 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:

![A client at 192.0.2.10 runs Browser tab 1 on ephemeral port 50514, Browser tab 2 on 50515 and an SSH client on 50600. A server at 203.0.113.80 listens on port 443 (web server) and port 22 (SSH server). Both browser tabs connect to 443 and the SSH client to 22. The three TCP connections are 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](../../../assets/diagrams/tcp-ports-sockets.svg)

*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.

![Comparison. Before sending: TCP does a three-way handshake; UDP just sends. Delivery: TCP acknowledges data and resends losses; UDP is best effort with no ACKs. Order: TCP is one ordered byte stream; UDP sends separate datagrams. Flow and congestion control: built into TCP; none in UDP, the application's job. Header size: TCP 20 to 60 bytes, UDP 8 bytes. Typical TCP uses: HTTPS 443, SSH 22, SMTP 25, IMAPS 993. Typical UDP uses: DNS 53, DHCP 67/68, NTP 123, QUIC 443](../../../assets/diagrams/tcp-vs-udp.svg)

*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.

![TCP handshake between a client at 192.0.2.10:50514 (CLOSED) and a server at 203.0.113.80:443 (LISTEN). 1: client sends SYN seq=1000 and enters SYN-SENT; server enters SYN-RECEIVED. 2: server sends SYN, ACK seq=5000 ack=1001; client becomes ESTABLISHED. 3: client sends ACK ack=5001; server becomes ESTABLISHED. Then the client sends 100 bytes of data at seq=1001, for example a TLS ClientHello, and the server answers ACK ack=1101](../../../assets/diagrams/tcp-handshake.svg)

*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:

![TCP teardown between the client 192.0.2.10:50514 and the server 203.0.113.80:443, both ESTABLISHED. 1: client sends FIN seq=1101 and enters FIN-WAIT-1. 2: server sends ACK ack=1102 and enters CLOSE-WAIT; client enters FIN-WAIT-2. The server application finishes and calls close(). 3: server sends FIN seq=5001 and enters LAST-ACK; client enters TIME-WAIT. 4: client sends ACK ack=5002; server becomes CLOSED. The client waits in TIME-WAIT for 2 × MSL, 60 seconds on Linux, then becomes CLOSED](../../../assets/diagrams/tcp-teardown.svg)

*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).

![The sender 192.0.2.10 sends seq=1001, 1000 bytes; the receiver 203.0.113.80 answers ACK ack=2001 win=64000. The segment seq=2001 is lost in the network. The segment seq=3001 arrives and the receiver repeats ACK ack=2001, a duplicate meaning still missing byte 2001. Duplicate ACKs or the retransmission timer make the sender resend seq=2001, and the receiver answers ACK ack=4001](../../../assets/diagrams/tcp-retransmission.svg)

*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*.

![Left: a client at 192.0.2.10 sends SYN to 198.51.100.20:8080, where the port is closed. The host answers RST, ACK and the client reports connection refused within milliseconds. Right: a client at 192.0.2.10 sends SYN to 198.51.100.30:8080, where a firewall drops it silently. The client retries the SYN twice more with no answer and reports connection timed out after the timeout expires](../../../assets/diagrams/tcp-refused-vs-timeout.svg)

*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.
