CloudAcademia
EN

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

Lab: TCP and UDP Sockets on Your Own Machine

Lab60 minBeginnerMarkdown

Showing raw Markdown: the renderer could not load.

## Goal
You write a small Transmission Control Protocol (TCP) echo server and a User Datagram Protocol (UDP) echo server in Python, talk to them with your own clients and with `nc`, and watch the sockets change state with `ss` (or `netstat`). Then you provoke the two classic failures, "connection refused" and "connection timed out", and see why one takes milliseconds and the other takes as long as you let it. Everything runs on your own computer, on `127.0.0.1`.

## Objectives
- Explain how a listening port and an ephemeral client port together identify a connection.
- Compare TCP and UDP by running both on the same port number and seeing how differently they behave.
- Observe a TCP connection go from ESTABLISHED to TIME-WAIT, and (optionally) capture the handshake and teardown with `tcpdump`.
- Identify listening sockets and connection states (LISTEN, ESTAB, TIME-WAIT, UNCONN) with `ss` or `netstat`.
- Reproduce and explain "connection refused" versus "connection timed out".

## Prerequisites
- A computer running Linux (with `ss` from iproute2), macOS or Windows 10/11.
- Python 3.10 or later, standard library only. This lab was tested with Python 3.14.7 and 3.11.8. Check yours with `python3 --version` (on Windows: `py --version`).
- `nc` (netcat), optional but recommended. Linux: package `netcat-openbsd` (Debian, Ubuntu) or `nmap-ncat` (Fedora, RHEL). macOS: built in. Windows: not built in; use the Python clients and `Test-NetConnection` instead. Outputs below come from OpenBSD netcat 1.226.
- Three terminal windows: one for each server and one for your commands.
- Optional, for Step 10 only: `tcpdump` and administrator rights (`sudo`) on Linux or macOS.
- [Lesson: Transport Layer: TCP, UDP and Ports](lesson.md) of this module.

> [!WARNING]
> Run every command in this lab against **your own computer only**: `127.0.0.1` and the documentation address `192.0.2.1` (RFC 5737), which is never assigned to a real host. Don't point `nc -z`, `probe.py` or any other connection test at systems you don't own or aren't explicitly authorized to test: probing other people's ports is port scanning, which may be illegal and breaks most providers' terms of service. The servers in this lab listen on `127.0.0.1` only, so nothing on your network can reach them.

## Architecture
<figure class="diagram" style="--dg-w: 980px"><svg xmlns="http://www.w3.org/2000/svg" class="dg" viewBox="0 0 980 480" width="980" height="480" role="img" aria-labelledby="tcp-lab-architecture-title tcp-lab-architecture-desc" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif" xml:lang="en">
<title id="tcp-lab-architecture-title">Lab architecture: TCP and UDP sockets on your own computer</title>
<desc id="tcp-lab-architecture-desc">Everything runs on your computer over the loopback interface, 127.0.0.1. The clients tcp_client.py, udp_client.py, nc and probe.py use ephemeral source ports. They talk to a TCP echo server on 127.0.0.1 port 9000, a UDP echo server on 127.0.0.1 port 9000, and port 9001 where nothing listens, which answers TCP with RST and UDP with an ICMP port unreachable message. You watch with ss -tan, ss -uln and, optionally with sudo, tcpdump -i lo. One probe goes to the documentation address 192.0.2.1 port 80, which never replies, so the connection times out.</desc>
<rect class="dg-bg" x="0.5" y="0.5" width="979" height="479" rx="16" fill="#ffffff" stroke="#e3e3dd"/>
<g class="dg-l2"><rect class="dg-tint" x="20" y="20" width="700" height="400" rx="16" fill="#f1f7f3" stroke="#a1ccb1" stroke-width="1.2" stroke-dasharray="6 5"/>
<g class="dg-icon" transform="translate(36 33) scale(0.7500)" fill="none" stroke="#15803d" stroke-width="2" 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="62" y="47" font-size="13" class="dg-ink" fill="#15803d" font-weight="700">Your computer · loopback interface (lo) · 127.0.0.1</text></g>
<rect class="dg-card" x="44" y="64" width="200" height="330" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(60 80) 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="102" y="101" font-size="15" class="dg-text" fill="#17171c" font-weight="700">Clients</text>
<text x="62" y="132" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">tcp_client.py</text>
<text x="62" y="152" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">udp_client.py</text>
<text x="62" y="172" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">nc</text>
<text x="62" y="192" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">probe.py</text>
<text x="62" y="230" font-size="12" class="dg-muted" fill="#5c5c68" font-weight="500">source: an ephemeral port</text>
<g class="dg-l4"><rect class="dg-tint" x="62" y="244" width="132" height="26" rx="13" fill="#f9ece7" stroke="#e4aa92" stroke-width="1.2"/><text x="128" y="261.5" font-size="12" class="dg-ink" fill="#c2410c" font-weight="700" text-anchor="middle">127.0.0.1:50980</text></g>
<rect class="dg-card" x="440" y="64" width="260" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l4"><g class="dg-icon" transform="translate(456 80) scale(1.2500)" fill="none" stroke="#c2410c" 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></g>
<g class="dg-l4"><text x="498" y="101" font-size="15" class="dg-ink" fill="#c2410c" font-weight="700">TCP echo server</text></g>
<text x="458" y="132" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">127.0.0.1:9000/tcp</text>
<g class="dg-l4"><path class="dg-stroke" d="M248 110H434" stroke="#c2410c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l4"><path class="dg-stroke" d="M427 104l8 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-bg-plain" x="323.34" y="98" width="37.32" height="24" rx="12" fill="#ffffff"/><text x="342" y="114.5" font-size="11.5" class="dg-ink" fill="#c2410c" font-weight="600" text-anchor="middle">TCP</text></g>
<rect class="dg-card" x="440" y="176" width="260" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-l1"><g class="dg-icon" transform="translate(456 192) scale(1.2500)" fill="none" stroke="#0369a1" 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></g>
<g class="dg-l1"><text x="498" y="213" font-size="15" class="dg-ink" fill="#0369a1" font-weight="700">UDP echo server</text></g>
<text x="458" y="244" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">127.0.0.1:9000/udp</text>
<g class="dg-l1"><path class="dg-stroke" d="M248 222H434" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><path class="dg-stroke" d="M427 216l8 6-8 6" stroke="#0369a1" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-l1"><rect class="dg-bg-plain" x="323.34" y="210" width="37.32" height="24" rx="12" fill="#ffffff"/><text x="342" y="226.5" font-size="11.5" class="dg-ink" fill="#0369a1" font-weight="600" text-anchor="middle">UDP</text></g>
<rect class="dg-card" x="440" y="288" width="260" height="106" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-warn"><g class="dg-icon" transform="translate(456 304) scale(1.2500)" fill="none" stroke="#b91c1c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></g></g>
<g class="dg-warn"><text x="498" y="325" font-size="15" class="dg-ink" fill="#b91c1c" font-weight="700">Nothing listening</text></g>
<text x="458" y="356" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">127.0.0.1:9001</text>
<text x="458" y="376" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">TCP: RST · UDP: ICMP unreachable</text>
<g class="dg-warn"><path class="dg-stroke" d="M248 334H434" stroke="#b91c1c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><path class="dg-stroke" d="M427 328l8 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-bg-plain" x="304.02" y="322" width="75.96" height="24" rx="12" fill="#ffffff"/><text x="342" y="338.5" font-size="11.5" class="dg-ink" fill="#b91c1c" font-weight="600" text-anchor="middle">TCP / UDP</text></g>
<rect class="dg-card" x="750" y="64" width="210" height="170" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(766 80) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></g>
<text x="808" y="101" font-size="15" class="dg-text" fill="#17171c" font-weight="700">Watch with</text>
<text x="768" y="132" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ss -tan</text>
<text x="768" y="152" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">ss -uln</text>
<text x="768" y="172" font-size="12.5" class="dg-text" fill="#17171c" font-weight="500" font-family="JetBrains Mono, ui-monospace, Menlo, Consolas, monospace">tcpdump -i lo</text>
<text x="768" y="192" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">(optional, needs sudo)</text>
<rect class="dg-card" x="750" y="270" width="210" height="140" rx="12" fill="#ffffff" stroke="#cfcfc8"/>
<g class="dg-icon-neutral" transform="translate(766 286) scale(1.2500)" fill="none" stroke="#17171c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></g>
<text x="808" y="307" font-size="14" class="dg-text" fill="#17171c" font-weight="700">192.0.2.1:80</text>
<text x="768" y="338" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">Documentation address</text>
<text x="768" y="358" font-size="13" class="dg-muted" fill="#5c5c68" font-weight="500">no reply → timeout</text>
<g class="dg-warn"><path class="dg-stroke" d="M144 394V450H855V416" 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="M849 423l6-8 6 8" stroke="#b91c1c" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>
<g class="dg-warn"><rect class="dg-bg-plain" x="416.94" y="438" width="166.12" height="24" rx="12" fill="#ffffff"/><text x="500" y="454.5" font-size="11.5" class="dg-ink" fill="#b91c1c" font-weight="600" text-anchor="middle">SYN, no reply → timeout</text></g>
</svg></figure>

*Figure 1. Two servers share the port number 9000, one for TCP and one for UDP. Port 9001 has no server, and `192.0.2.1` never answers.*

## Steps

### Step 1 — Create a working folder
You'll write five small scripts. Keep them in one folder so cleanup is a single command.

Linux and macOS:

```bash
mkdir -p ~/tcp-lab && cd ~/tcp-lab
```

Windows (PowerShell):

```powershell
New-Item -ItemType Directory -Force "$HOME\tcp-lab"; Set-Location "$HOME\tcp-lab"
```

Use this folder in all three terminals. On Windows, type `py` wherever this lab says `python3`.

### Step 2 — Look before you touch anything
Before starting your own servers, see what your computer already listens on, and which range it uses for ephemeral ports.

**Linux:**

```bash
ss -tuln
cat /proc/sys/net/ipv4/ip_local_port_range
```

Expected output (abbreviated; your list differs):

```text
Netid State  Recv-Q Send-Q   Local Address:Port  Peer Address:Port
udp   UNCONN 0      0        127.0.0.53%lo:53         0.0.0.0:*
udp   UNCONN 0      0            127.0.0.1:323        0.0.0.0:*
udp   UNCONN 0      0              0.0.0.0:5353       0.0.0.0:*
tcp   LISTEN 0      4096     127.0.0.53%lo:53         0.0.0.0:*
tcp   LISTEN 0      4096         127.0.0.1:631        0.0.0.0:*
32768	60999
```

On a typical desktop you'll see a local Domain Name System (DNS) resolver on port 53 (here `systemd-resolved`, on `127.0.0.53`), the time service on UDP 323, multicast DNS on UDP 5353 and a printing service on TCP 631. Most of them listen on loopback addresses only. The last line is the ephemeral port range: Linux uses 32768–60999 by default, not the 49152–65535 range from RFC 6335.

**macOS:**

```bash
netstat -an -p tcp | grep LISTEN
sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last
```

**Windows (PowerShell):**

```powershell
Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Select-Object LocalAddress, LocalPort, OwningProcess
netsh int ipv4 show dynamicport tcp
```

On macOS and Windows the dynamic range is 49152–65535 by default.

> [!NOTE]
> The macOS and Windows commands were not run for this guide, so their output isn't shown; the columns are self-explanatory. Port 9000 must be free for this lab. If something already listens on it, change `PORT` in every script to another free port above 1024, such as 9500.

### Step 3 — Write and start the TCP echo server
A server needs a fixed, known port so clients can find it. This one listens on `127.0.0.1:9000` and sends back every byte it receives. Save it as `tcp_server.py`:

```python
"""TCP echo server: accepts connections on 127.0.0.1:9000 and sends back every byte it receives."""
import socket
import sys

HOST, PORT = "127.0.0.1", 9000

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
    if sys.platform != "win32":
        # Allow a restart while old connections are still in TIME-WAIT.
        # (On Windows this option means something else, so it is skipped there.)
        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind((HOST, PORT))
    srv.listen()
    print(f"TCP echo server listening on {HOST}:{PORT}", flush=True)
    try:
        while True:
            conn, peer = srv.accept()  # blocks until a handshake completes
            with conn:
                print(f"connection from {peer[0]}:{peer[1]}", flush=True)
                while data := conn.recv(1024):  # b"" means the client sent FIN
                    conn.sendall(data)
                print(f"{peer[0]}:{peer[1]} closed the connection", flush=True)
    except KeyboardInterrupt:
        print("server stopped")
```

- `SOCK_STREAM` asks for TCP. `bind()` claims the address and port; `listen()` turns the socket into a listening socket.
- `accept()` returns only after a client has completed the three-way handshake. The operating system did the handshake; your program just picks up the result.
- `recv()` returns an empty result when the client has sent FIN. That is how a TCP program learns that the other side closed.

In **terminal 1**, start it and leave it running:

```bash
python3 tcp_server.py
```

Expected output:

```text
TCP echo server listening on 127.0.0.1:9000
```

### Step 4 — Find the listening socket
In **terminal 3** (your command terminal), ask the operating system who listens on port 9000. The filter `'sport = :9000'` (source port, which for a listening socket is the local port) keeps the output short.

**Linux:**

```bash
ss -tlnp 'sport = :9000'
```

Expected output (your process ID differs):

```text
State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0      128        127.0.0.1:9000      0.0.0.0:*    users:(("python3",pid=4242,fd=3))
```

- `LISTEN` on `127.0.0.1:9000`: only programs on this computer can connect.
- `Peer Address:Port` is `0.0.0.0:*` because a listening socket has no peer yet.
- `Send-Q 128` is the backlog: how many finished handshakes may wait for `accept()`.
- `users:(("python3",pid=…))` is the owning process. You see it without `sudo` because the socket is yours.

**macOS:** `lsof -nP -iTCP:9000 -sTCP:LISTEN`. **Windows (PowerShell):** `Get-NetTCPConnection -LocalPort 9000`.

### Step 5 — Connect and watch the connection
Now you need a client. It connects, prints its own address and port and the server's, sends a message and reads the echo. An optional argument keeps the connection open for some seconds so you can inspect it. Save it as `tcp_client.py`:

```python
"""TCP client: connects to the echo server, sends one message, prints the reply."""
import socket
import sys
import time

HOST, PORT = "127.0.0.1", 9000
HOLD = int(sys.argv[1]) if len(sys.argv) > 1 else 0  # seconds to keep the connection open

with socket.create_connection((HOST, PORT), timeout=5) as sock:
    local, remote = sock.getsockname(), sock.getpeername()
    print(f"connected: {local[0]}:{local[1]} -> {remote[0]}:{remote[1]}")
    sock.sendall(b"hello over TCP")
    print("reply:", sock.recv(1024).decode())
    time.sleep(HOLD)
print("closed")
```

Notice that the client never chooses its own port: `create_connection()` lets the operating system pick an ephemeral one.

In terminal 3, run the client in the background with a 15-second hold, then list the TCP sockets on port 9000 at once. On Linux:

```bash
python3 tcp_client.py 15 &
ss -tan '( sport = :9000 or dport = :9000 )'
```

Expected output (your ephemeral port differs; the client's lines may appear before or after the table):

```text
connected: 127.0.0.1:36784 -> 127.0.0.1:9000
reply: hello over TCP
State  Recv-Q Send-Q Local Address:Port  Peer Address:Port
LISTEN 0      128        127.0.0.1:9000       0.0.0.0:*
ESTAB  0      0          127.0.0.1:36784    127.0.0.1:9000
ESTAB  0      0          127.0.0.1:9000     127.0.0.1:36784
```

Read the three lines:
- The `LISTEN` socket is still there: it keeps waiting for the *next* client.
- The connection appears **twice**, once from each end, because both ends live on your computer. The client's side is `127.0.0.1:36784 → 127.0.0.1:9000`; the server's side is the mirror image.
- `36784` is in the ephemeral range from Step 2. Run the client again and you get a different port.

In terminal 1, the server logged the connection:

```text
connection from 127.0.0.1:36784
```

On macOS, run the client the same way and use `netstat -an -p tcp | grep 9000`. On Windows, start `py tcp_client.py 15` in an extra terminal and run `Get-NetTCPConnection -LocalPort 9000; Get-NetTCPConnection -RemotePort 9000` in terminal 3 within 15 seconds.

### Step 6 — See TIME-WAIT
Wait until the client prints `closed` (15 seconds), then look again:

```bash
ss -tan '( sport = :9000 or dport = :9000 )'
ss -tano state time-wait '( sport = :9000 or dport = :9000 )'
```

Expected output:

```text
State     Recv-Q Send-Q Local Address:Port  Peer Address:Port
LISTEN    0      128        127.0.0.1:9000       0.0.0.0:*
TIME-WAIT 0      0          127.0.0.1:36784    127.0.0.1:9000
Recv-Q Send-Q Local Address:Port  Peer Address:Port
0      0          127.0.0.1:36784    127.0.0.1:9000 timer:(timewait,58sec,0)
```

- Only one line is left for the old connection, and it is on the **client's** port. The client closed first (its `with` block ended), so the client is the side that waits in TIME-WAIT. The server's side went straight to CLOSED after its own FIN was acknowledged.
- `-o` shows timers: `timewait,58sec` counts down from 60 seconds, the fixed TIME-WAIT time on Linux. Run the command again after a minute: the line is gone.

The server logged the close in terminal 1:

```text
127.0.0.1:36784 closed the connection
```

On macOS and Windows, `netstat -an -p tcp | grep 9000` (macOS) or `netstat -an -p tcp | findstr 9000` (Windows) shows the same connection as `TIME_WAIT`. Their timers are different from Linux's.

### Step 7 — Talk to the server with netcat
Your client isn't special: any TCP program can talk to the server. Netcat (`nc`) connects and then copies your keyboard to the socket and the socket to your screen.

```bash
nc 127.0.0.1 9000
```

Type `hello from nc` and press Enter. The server echoes it:

```text
hello from nc
hello from nc
```

The first line is what you typed, the second is the echo. Press **Ctrl+C** to quit. Terminal 1 logs the connection and the close, each with a new ephemeral port.

> [!NOTE]
> There are several netcat implementations with slightly different options and messages: OpenBSD netcat (Debian, Ubuntu, and the base of macOS's `nc`), Nmap's `ncat` (Fedora, RHEL) and the old "traditional" netcat. The basic `nc <host> <port>` works in all of them. On Windows, skip the `nc` commands and use the Python clients.

### Step 8 — Add a UDP server on the same port number
TCP and UDP have separate port spaces, so a UDP server can use port 9000 too. Save this as `udp_server.py`:

```python
"""UDP echo server: receives datagrams on 127.0.0.1:9000 and sends each one back."""
import socket

HOST, PORT = "127.0.0.1", 9000

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
    srv.bind((HOST, PORT))
    print(f"UDP echo server listening on {HOST}:{PORT}", flush=True)
    try:
        while True:
            data, peer = srv.recvfrom(2048)  # no accept(): every datagram stands alone
            print(f"datagram from {peer[0]}:{peer[1]}: {data.decode(errors='replace')}", flush=True)
            srv.sendto(data, peer)
    except KeyboardInterrupt:
        print("server stopped")
```

Compare it with the TCP server: `SOCK_DGRAM` instead of `SOCK_STREAM`, no `listen()`, no `accept()` and no connection object. Every datagram arrives with its sender's address, and the reply goes back to that address.

In **terminal 2**, start it:

```bash
python3 udp_server.py
```

```text
UDP echo server listening on 127.0.0.1:9000
```

In terminal 3, list TCP and UDP sockets on port 9000 together:

```bash
ss -tuln 'sport = :9000'
```

Expected output:

```text
Netid State  Recv-Q Send-Q Local Address:Port Peer Address:Port
udp   UNCONN 0      0          127.0.0.1:9000      0.0.0.0:*
tcp   LISTEN 0      128        127.0.0.1:9000      0.0.0.0:*
```

Two sockets, same address, same port number, different protocols. The UDP one is `UNCONN` (unconnected), not `LISTEN`: UDP has no connections to listen for.

Now the client. Save it as `udp_client.py`:

```python
"""UDP client: sends one datagram to 127.0.0.1 and waits up to 2 seconds for an answer."""
import socket
import sys

HOST = "127.0.0.1"
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 9000

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.settimeout(2)
    sock.connect((HOST, PORT))  # for UDP, connect() only sets the default destination: nothing is sent
    local = sock.getsockname()
    print(f"sending from {local[0]}:{local[1]} to {HOST}:{PORT}")
    sock.send(b"hello over UDP")
    try:
        print("reply:", sock.recv(2048).decode())
    except TimeoutError:
        print("no reply within 2 s (lost, filtered, or nobody listening)")
    except ConnectionError:
        print("error: port unreachable (an ICMP message said nobody is listening)")
```

Run it:

```bash
python3 udp_client.py
```

Expected output:

```text
sending from 127.0.0.1:40760 to 127.0.0.1:9000
reply: hello over UDP
```

Terminal 2 shows `datagram from 127.0.0.1:40760: hello over UDP`. Then try netcat in UDP mode (`-u`), type a line, read the echo and press Ctrl+C:

```bash
nc -u 127.0.0.1 9000
```

Run `ss -tan '( sport = :9000 or dport = :9000 )'` and `ss -uan 'sport = :9000'` again after the UDP client: there is no ESTAB and no TIME-WAIT for UDP. Nothing was set up, so nothing has to be torn down.

### Step 9 — Connection refused versus connection timed out
This is the troubleshooting skill from the lesson. You'll make a connection fail in three ways and time each one. Save this as `probe.py`:

```python
"""Try a TCP connection and report how it ended and how long it took."""
import socket
import sys
import time

host, port = sys.argv[1], int(sys.argv[2])
timeout = float(sys.argv[3]) if len(sys.argv) > 3 else 3

start = time.monotonic()
try:
    with socket.create_connection((host, port), timeout=timeout):
        result = "open: handshake completed"
except ConnectionRefusedError:
    result = "refused: the host answered with RST"
except TimeoutError:
    result = "timed out: no answer at all"
except OSError as exc:
    result = f"error: {exc.strerror}"
print(f"{host}:{port} -> {result} after {time.monotonic() - start:.2f} s")
```

Probe the open port, a closed port on your own machine, and the documentation address `192.0.2.1`, which is never assigned to anyone:

```bash
python3 probe.py 127.0.0.1 9000
python3 probe.py 127.0.0.1 9001
python3 probe.py 192.0.2.1 80 3
```

Expected output:

```text
127.0.0.1:9000 -> open: handshake completed after 0.01 s
127.0.0.1:9001 -> refused: the host answered with RST after 0.01 s
192.0.2.1:80 -> timed out: no answer at all after 3.01 s
```

- **Port 9000:** the handshake completes. Terminal 1 logs a connection.
- **Port 9001:** your computer received the SYN, found no listening socket and answered RST at once: *connection refused*.
- **`192.0.2.1`:** the SYN leaves your computer and nobody ever answers, so the client waits for the full timeout you gave it (3 s): *timed out*. Without a timeout, Linux keeps retrying the SYN for a little over two minutes before giving up.

`<timeout>`, the optional third argument, is the number of seconds to wait. Try `python3 probe.py 192.0.2.1 80 10` and the result arrives after 10 seconds instead: the delay is set by the *client*, not by the network.

The same tests with netcat (`-v` verbose, `-z` connect without sending data, `-w 3` timeout):

```bash
nc -vz 127.0.0.1 9000
nc -vz 127.0.0.1 9001
nc -vz -w 3 192.0.2.1 80
```

```text
Connection to 127.0.0.1 9000 port [tcp/*] succeeded!
nc: connect to 127.0.0.1 port 9001 (tcp) failed: Connection refused
nc: connect to 192.0.2.1 port 80 (tcp) timed out: Operation in progress
```

The text in brackets may show a service name from your system's services list instead of `*`. On Windows (PowerShell), the equivalent check is `Test-NetConnection -ComputerName 127.0.0.1 -Port 9001`, which reports `TcpTestSucceeded : False` for both kinds of failure; use `probe.py` to see the difference.

Finally, UDP to a closed port:

```bash
python3 udp_client.py 9001
```

```text
sending from 127.0.0.1:56778 to 127.0.0.1:9001
error: port unreachable (an ICMP message said nobody is listening)
```

Your computer answered the datagram with an Internet Control Message Protocol (ICMP) "port unreachable" message, and because the client used `connect()`, the operating system reported it as an error. Across a real network that ICMP message is often filtered, and the client would just print `no reply within 2 s`: with UDP, "closed" and "lost" can look identical.

> [!NOTE]
> Timings and messages vary by operating system. On Windows, a refused connection can take about two seconds, because the client retries a couple of times after RST, and the UDP error may be reported as a connection *reset*; the script catches both. Your network may also answer for `192.0.2.1` quickly with "No route to host" or "Network is unreachable" (the script prints `error: …`) if it has no route to that range. That is a third kind of failure, coming from the network layer rather than the target.

### Step 10 (optional) — Capture the handshake with tcpdump
This step needs administrator rights. Skip it if you don't have them; the output below shows what you would see.

In terminal 3, start a capture on the loopback interface (`lo` on Linux, `lo0` on macOS). `-n` shows numbers instead of names:

```bash
sudo tcpdump -i lo -n 'tcp port 9000 or tcp port 9001 or icmp'
```

In an extra terminal, run the client once and probe the closed port once:

```bash
python3 tcp_client.py
python3 probe.py 127.0.0.1 9001
python3 udp_client.py 9001
```

Stop the capture with Ctrl+C. Expected output (timestamps and TCP options shortened; your ports, sequence numbers and windows differ):

```text
IP 127.0.0.1.37246 > 127.0.0.1.9000: Flags [S], seq 646296056, win 65495, options [mss 65495,…], length 0
IP 127.0.0.1.9000 > 127.0.0.1.37246: Flags [S.], seq 1082532584, ack 646296057, win 65483, options [mss 65495,…], length 0
IP 127.0.0.1.37246 > 127.0.0.1.9000: Flags [.], ack 1, win 64, length 0
IP 127.0.0.1.37246 > 127.0.0.1.9000: Flags [P.], seq 1:15, ack 1, win 64, length 14
IP 127.0.0.1.9000 > 127.0.0.1.37246: Flags [.], ack 15, win 64, length 0
IP 127.0.0.1.9000 > 127.0.0.1.37246: Flags [P.], seq 1:15, ack 15, win 64, length 14
IP 127.0.0.1.37246 > 127.0.0.1.9000: Flags [.], ack 15, win 64, length 0
IP 127.0.0.1.37246 > 127.0.0.1.9000: Flags [F.], seq 15, ack 15, win 64, length 0
IP 127.0.0.1.9000 > 127.0.0.1.37246: Flags [F.], seq 15, ack 16, win 64, length 0
IP 127.0.0.1.37246 > 127.0.0.1.9000: Flags [.], ack 16, win 64, length 0
IP 127.0.0.1.34924 > 127.0.0.1.9001: Flags [S], seq 1486054817, win 65495, options [mss 65495,…], length 0
IP 127.0.0.1.9001 > 127.0.0.1.34924: Flags [R.], seq 0, ack 1486054818, win 0, length 0
IP 127.0.0.1 > 127.0.0.1: ICMP 127.0.0.1 udp port 9001 unreachable, length 50
```

Match it to the lesson:
- Lines 1–3: the three-way handshake, `[S]`, `[S.]`, `[.]`. The initial sequence numbers (ISNs) are random; the SYN-ACK acknowledges the client's ISN + 1. From line 3, `tcpdump` prints sequence numbers relative to the ISN.
- Lines 4–7: `hello over TCP` is 14 bytes (`seq 1:15`, `length 14`), acknowledged with `ack 15`, then echoed back and acknowledged the same way.
- Lines 8–10: the teardown. The client's FIN, then the server's FIN combined with the ACK of the client's FIN (`ack 16`: a FIN counts as one byte), then the client's final ACK. Combining two steps into one segment is common, so you often see three teardown segments instead of four.
- Lines 11–12: a SYN to the closed port 9001, answered with `[R.]` (RST, ACK). That is "connection refused" on the wire.
- Line 13: the ICMP port unreachable message for the UDP datagram to 9001.
- The maximum segment size (MSS) of 65495 and the large windows are typical for loopback, whose maximum transmission unit (MTU) is 65536. On Ethernet you would see `mss 1460`.

> [!NOTE]
> This capture was recorded with `tcpdump` on Linux. A SYN to `192.0.2.1` would show up as the same `[S]` line repeated a few times with growing gaps and no answer, which is how a timeout looks on the wire. To see it, capture on your main interface (for example `eth0`, `en0` or the name `ip route show default` reports) instead of loopback.

## Verification
You have completed the lab if you can answer "yes" to each check:

| Check | How to confirm |
|---|---|
| The TCP server listens on `127.0.0.1:9000` | `ss -tlnp 'sport = :9000'` shows `LISTEN` and your `python3` process |
| You saw one connection from both ends | Step 5 shows two `ESTAB` lines that mirror each other, with an ephemeral port in your range from Step 2 |
| You saw TIME-WAIT on the side that closed first | Step 6 shows `TIME-WAIT` on the client's ephemeral port only, with a timer of at most 60 s on Linux |
| TCP and UDP share the port number 9000 | `ss -tuln 'sport = :9000'` shows a `tcp LISTEN` and a `udp UNCONN` line |
| You can tell refused from timed out | `probe.py` reports `refused` in about 0.01 s for port 9001 and `timed out` after your chosen timeout for `192.0.2.1` |

## Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `OSError: [Errno 98] Address already in use` (Linux), `[Errno 48]` (macOS) or `[WinError 10048]` (Windows) when starting a server | Another copy of the server is still running, or something else uses port 9000 | Find it with `ss -tulnp 'sport = :9000'` (Linux), `lsof -nP -i :9000` (macOS) or `Get-NetTCPConnection -LocalPort 9000` (Windows); stop it, or change `PORT` in all scripts |
| `ConnectionRefusedError: [Errno 111] Connection refused` from `tcp_client.py` | The TCP server isn't running, or listens on a different port | Check terminal 1; start `python3 tcp_server.py` again |
| `udp_client.py` prints `no reply within 2 s` although the UDP server should be running | The UDP server isn't running, or a local firewall drops loopback UDP | Check terminal 2 and `ss -uln 'sport = :9000'` |
| `nc: command not found` | Netcat isn't installed | Install `netcat-openbsd` or `nmap-ncat`, or skip the `nc` commands; the Python clients do the same job |
| `probe.py 192.0.2.1 80` prints `error: No route to host` or `Network is unreachable` immediately | Your system or network has no route for `192.0.2.0/24`, or a router answers with ICMP | That's fine: it is a network-layer failure, not a timeout. Compare it with the lesson's error list |
| The `ESTAB` lines don't appear in Step 5 | More than 15 s passed before `ss` ran, or the client failed | Run the two commands together as shown, or increase the hold time: `python3 tcp_client.py 30 &` |
| `tcpdump: lo: No such device exists` | On macOS the loopback interface is `lo0` | Use `sudo tcpdump -i lo0 -n …` |

## Challenge (optional)
1. Change `tcp_server.py` so that the **server** closes the connection right after sending the echo (break out of the loop after the first `sendall()`). Which side shows TIME-WAIT now? Then remove the `SO_REUSEADDR` line, run a client, stop the server and start it again within a minute. What happens, and why does almost every real server set `SO_REUSEADDR`?
2. Make the server listen on `0.0.0.0` instead of `127.0.0.1` and check the difference with `ss -tln`. Is it now reachable from another device on your network? Does your host firewall allow it? Change it back when you are done.
3. Open ten connections at once (for example, `for i in $(seq 10); do python3 tcp_client.py 20 & done`) and count them with `ss -tan '( dport = :9000 )' | wc -l`. Which part of the 4-tuple differs between them?
4. Send a 5,000-byte message with `tcp_client.py` and read it with a single `recv(1024)`. What arrives? What does that tell you about TCP as a byte stream, and how would you design a message format on top of it?

## Cleanup
Stop both servers: press **Ctrl+C** in terminal 1 and terminal 2. Each prints `server stopped`. Close any `nc` sessions with Ctrl+C and stop `tcpdump` if it is still running.

Check that nothing is left on port 9000 (Linux):

```bash
ss -tuln 'sport = :9000'
```

```text
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
```

Only the header line means both servers are gone. If a server is still running (for example, you closed its terminal), stop it with `pkill -f tcp_server.py; pkill -f udp_server.py` on Linux or macOS, or `Get-Process python*` and `Stop-Process -Id <pid>` on Windows. `<pid>` is the process ID shown by `ss -tulnp` or `Get-NetTCPConnection` (the `OwningProcess` column).

Remove the folder and the five scripts.

Linux and macOS:

```bash
cd ~ && rm -r ~/tcp-lab
```

Windows (PowerShell):

```powershell
Set-Location $HOME; Remove-Item -Recurse -Force "$HOME\tcp-lab"
```

TIME-WAIT entries disappear by themselves within a minute or so. No system settings were changed, so there is nothing else to undo.

## What you learned
- A server binds a fixed port and listens; each client gets an ephemeral port from the operating system, and the 4-tuple names the connection. On one machine you see every connection twice, once from each end.
- TCP and UDP have separate port spaces. TCP shows LISTEN, ESTAB and TIME-WAIT; UDP only UNCONN, because there are no connections.
- The side that closes first holds TIME-WAIT (60 s on Linux). It is normal and goes away on its own.
- "Connection refused" is an answer (RST) and arrives in milliseconds. "Connection timed out" is silence, and how long it takes depends on the client's timeout.
- `ss` (or `netstat`, `lsof`, `Get-NetTCPConnection`) and, with administrator rights, `tcpdump` show you exactly what the transport layer is doing.