# TCP, UDP and ports: refused is not timed out

Watch a real TCP connection open and close, learn what refused, timed out and open each tell you, see UDP send with no reply, and find what is listening with ss.

Course: [Networking for DevOps](https://devops.rajeev.pro/courses/networking), lesson 3. About 25 minutes, beginner. Source: https://devops.rajeev.pro/courses/networking/03-tcp-udp-and-ports

## What you will learn

- Follow the TCP handshake, data and close in a real capture
- Tell refused, timed out and open apart, and know which layer each points at
- Explain when UDP is used instead of TCP
- Find which process listens on which port with ss

> **Lab status.** **Verified lab:** two Alpine containers on a Docker network: a server listening with `socat` on TCP 8080 and UDP 9000, and a client using `nc`, `tcpdump` and `ss`. The output shown is real. <br />**Cloud lab:** none needed.

Most "can't connect" problems are solved by reading one error message correctly. TCP gives you three different
answers, and each one points at a different place.

The lab is two containers: a server at `10.50.0.10` (TCP 8080 answers "hello from srv", UDP 9000 prints what it
gets) and a client at `10.50.0.2`.

## A TCP connection, start to finish

> **Figure.** Animated sequence diagram between client 10.50.0.2:47158 and server 10.50.0.10:8080. A SYN travels to the server, a SYN-ACK returns, and an ACK travels back. The connection is ready for data after the third packet.
>
> The three-way handshake: SYN, SYN-ACK, ACK. Turn on reduced motion to see the completed exchange at once.

```text
$ tcpdump -i eth0 -n -c 10 host 10.50.0.10 and port 8080 & nc 10.50.0.10 8080
hello from srv
IP 10.50.0.2.47158 > 10.50.0.10.8080: Flags [S], seq 795707756, ...
IP 10.50.0.10.8080 > 10.50.0.2.47158: Flags [S.], seq 29718999, ack 795707757, ...
IP 10.50.0.2.47158 > 10.50.0.10.8080: Flags [.], ack 1, ...
IP 10.50.0.10.8080 > 10.50.0.2.47158: Flags [P.], seq 1:16, ack 1, ... length 15
IP 10.50.0.2.47158 > 10.50.0.10.8080: Flags [.], ack 16, ...
IP 10.50.0.10.8080 > 10.50.0.2.47158: Flags [F.], seq 16, ack 1, ...
IP 10.50.0.2.47158 > 10.50.0.10.8080: Flags [F.], seq 1, ack 17, ...
```

(Timestamps and options trimmed.) Before one byte of data, three packets set up the connection: that **round trip
is why connecting across the world feels slow**, and why connection reuse and keep-alive matter. Every byte is
then acknowledged, so TCP can resend what's lost. The client picked a random high **ephemeral port** (47158); the
server's port is fixed (8080). Those four values, two IPs and two ports, identify the connection.

## Open, refused or timed out

The single most useful skill in this lesson:

> **Figure.** Three columns. Open: nc -zv 10.50.0.10 8080, SYN then SYN-ACK, succeeded; something is listening, go up a layer. Refused: nc -zv 10.50.0.10 8081, SYN answered by RST in 0.3 ms; the host is up but nothing listens, the app is down, on the wrong port, or bound to 127.0.0.1. Timed out: nc to 10.50.0.99, SYN with no answer; a firewall dropped it, there is no route, or the host isn't there.

```text
$ nc -zv 10.50.0.10 8080
Connection to 10.50.0.10 8080 port [tcp/http-alt] succeeded!
$ nc -zv 10.50.0.10 8081
nc: connect to 10.50.0.10 port 8081 (tcp) failed: Connection refused
$ nc -zv -w 3 10.50.0.99 8080
nc: connect to 10.50.0.99 port 8080 (tcp) timed out: Operation in progress
```

On the wire, the refused port answered the SYN with a reset, `Flags [R.]`, 0.3 milliseconds later. **Refused is
fast and means you reached the host**: look at the app. **A timeout is slow and means silence**: look at the path,
firewalls and security groups. Cloud firewalls drop rather than refuse, which is why a missing security group rule
always looks like a timeout.

## UDP: just send

UDP has no handshake, no acknowledgements and no connection. One datagram goes out; nothing comes back unless the
application sends its own reply.

> **Figure.** Two columns. TCP, a reliable ordered stream: handshake first, every byte acknowledged and resent, closed with FIN; used by HTTP, SSH, TLS and databases; 8 packets for 15 bytes in the lab. UDP, single datagrams: no handshake, lost is lost, the app handles retries; used by DNS lookups, NTP, voice and video, StatsD and QUIC; 1 packet, no reply.

```text
$ tcpdump -i eth0 -n -c 1 udp port 9000 & echo hi | nc -u -w1 10.50.0.10 9000
IP 10.50.0.2.50055 > 10.50.0.10.9000: UDP, length 3
```

The server printed `hi`; the client never learned whether it arrived. That's fine for a DNS lookup (ask again if
no answer comes) or a video frame (a late frame is useless anyway). HTTP/3 runs on **QUIC**, which builds its own
reliability on top of UDP to avoid TCP's slower setup.

## What is listening

On the server, `ss` lists every socket. `-t` TCP, `-u` UDP, `-l` listening, `-n` numbers instead of names, and
`-p` adds the process (when you have permission):

```text
$ ss -tlnu
Netid State  Recv-Q Send-Q Local Address:Port  Peer Address:Port
udp   UNCONN 0      0         127.0.0.11:51087      0.0.0.0:*
udp   UNCONN 0      0            0.0.0.0:9000       0.0.0.0:*
tcp   LISTEN 0      4096      127.0.0.11:45011      0.0.0.0:*
tcp   LISTEN 0      5            0.0.0.0:8080       0.0.0.0:*
```

`0.0.0.0:8080` means "port 8080 on every interface", reachable from outside. A service on `127.0.0.1:8080` would
accept only local connections, a classic reason for "works on the server, refused from my laptop". (The
`127.0.0.11` lines are Docker's built-in DNS resolver.) Drop `-l` to see established connections instead.

Ports below 1024 are well-known (22 SSH, 53 DNS, 80 HTTP, 443 HTTPS) and need root to bind on Linux; your apps
usually listen on higher ones such as 3000 or 8080 behind a proxy (lesson 9).

## Mission: Three answers from one server

Run the server container listening on TCP 8080. From a client container, get one open, one refused and one timed-out result, capture the refused one with tcpdump to see the reset, and list the server's sockets with ss.

- You need: Docker
- You'll have: ~/ports.txt

```sh
$ docker network create --subnet 10.50.0.0/24 lab-net
$ docker run -d --name srv --network lab-net --ip 10.50.0.10 alpine:3.22 \
    sh -c 'apk add -q socat iproute2; socat TCP-LISTEN:8080,fork,reuseaddr SYSTEM:"echo hello"'
$ docker run --rm --network lab-net --cap-add NET_ADMIN --cap-add NET_RAW alpine:3.22 sh -c '
    apk add -q netcat-openbsd tcpdump
    nc -zv 10.50.0.10 8080; nc -zv 10.50.0.10 8081; nc -zv -w 3 10.50.0.99 8080
    tcpdump -n -c 2 port 8081 & sleep 1; nc -z 10.50.0.10 8081; sleep 1' > ~/ports.txt 2>&1
$ docker exec srv ss -tln >> ~/ports.txt
$ docker rm -f srv && docker network rm lab-net
```

You should see succeeded, refused, timed out, then a `[S]` and an `[R.]` packet.

## Try it

- Start the two lab containers and connect with `nc -zv` to an open and a closed port.
- Capture a connection with tcpdump and find SYN, SYN-ACK and ACK.
- Connect to an address that doesn't exist and time how long it takes to fail.
- Run `ss -tlnu` on the server and match each line to a service.
- Do the mini mission and keep `~/ports.txt`.

## Quiz

1. You get "Connection refused" instantly. What is the most likely cause?
   - A firewall is dropping packets
   - **The host is up but nothing is listening on that port** (answer)
   - DNS is broken
   - The cable is unplugged
   Why: The host answered your SYN with a reset. Something is wrong with the app or the port it listens on, not the path.

2. A connection hangs and then "timed out". Where do you look first?
   - The application logs
   - **The path, firewalls and security groups, because the SYN got no answer at all** (answer)
   - The TLS certificate
   - The database
   Why: Dropped packets produce silence. Refused means you reached the host; a timeout means you probably didn't.

3. Why do DNS lookups normally use UDP?
   - UDP is encrypted
   - **A lookup is one small question and one small answer, so a handshake would double the time** (answer)
   - TCP can't carry DNS
   - UDP guarantees delivery
   Why: UDP skips the handshake. DNS falls back to TCP for large answers and zone transfers.

4. In ss -tlnp, a service shows Local Address 127.0.0.1:5432. Can another machine connect to it?
   - Yes
   - **No, it listens only on the loopback interface** (answer)
   - Only over UDP
   - Only with a firewall rule
   Why: Binding to 127.0.0.1 accepts connections from the same machine only. 0.0.0.0 means every interface.

## Resources

- [Transmission Control Protocol (RFC 9293)](https://www.rfc-editor.org/rfc/rfc9293) (IETF)
- [ss(8) manual](https://man7.org/linux/man-pages/man8/ss.8.html) (man7.org)
- [High Performance Browser Networking, chapter 2 (TCP)](https://hpbn.co/building-blocks-of-tcp/) (Ilya Grigorik)
