What TCP promises and what it does not

TCP delivers your data in order, or it reports an error. How soon it reports depends on timers you did not set. The two errors, refused and timed out, show two different ways a connection fails.

Part 3 of 9 · Networking5 min read
serverSYNSYN-ACKACKthree packets open itSYN, SYN-ACK, ACKport 9001refused: instant nonothing listens on that porttimed out: silenceit waits about 2 minutesnc -zv -w 3 host portset your own deadlineTCP will wait minutesretries wait longerabout 2 minutes in all

One request to a service fails at once with “connection refused”. Another hangs for two minutes and then says “timed out”. Both mean that the connection did not open, but the causes are different, and so are the fixes. To tell them apart, we need to see what happens before the first byte of data moves.

Bub has the address from parts 1 and 2. The letter must arrive complete, so Bub sends it as a registered letter: the receiver confirms each delivery.

What TCP is

IP, from part 1, delivers single packets. It makes no promise about them. A packet can be lost, arrive twice, or arrive after a later one. TCP is the set of rules that fixes this for the two programs that talk. It opens a connection, numbers every piece of data, and waits for the other side to confirm what arrived. When a confirmation does not come, it sends the data again. At the other end, the pieces are put back in order.

In the picture, a missing receipt means that Bub sends a new copy. Web pages and databases use TCP.

senderreceiverpieces1234lostreceiptsok 1ok 2ok 4?no receipt for 3so TCP sends 3 again
TCP numbers the pieces and waits for a receipt. A piece without a receipt is sent again.

What a port is

An IP address finds a machine. A machine runs many programs, so a packet must also say which program it is for. That is the job of a port. In the picture, the address is the house and the port is one room inside it.

A program that wants to receive connections tells the kernel to give it whatever arrives at one port. This is called listening. A web server usually listens on port 80 or 443, and a Postgres database on port 5432. Start a small server on port 8080 and list the ports that listen:

Shell
docker run --rm alpine sh -c 'apk add -q iproute2 netcat-openbsd &&
(nc -l 8080 >/dev/null &) && sleep 1 && ss -ltn'  
State  Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0      1            0.0.0.0:8080      0.0.0.0:*

Here is what each marked part does:

  1. 1nc -l 8080 (netcat) listens on port 8080. The & at the end runs it in the background.
  2. 2ss -ltn lists sockets. The option -l shows listening ones, -t shows TCP, and -n shows numbers instead of names.

LISTEN means that a program waits at the port. The address 0.0.0.0 means every address of this machine.

10.1.5.5:808080web server5432database8080nc: LISTENthe IP address finds the housethe port finds the door
The address finds the machine, and the port finds the program.

Three packets open a connection

Before any data moves, the two sides agree to talk. This is the handshake. Start a server on port 8080, record the packets with tcpdump, and connect once:

Shell
docker run --rm --cap-add NET_RAW  \
alpine sh -c 'apk add -q netcat-openbsd tcpdump
nc -l 8080 >/dev/null &
sleep 1
tcpdump -nn -l -i lo -c 3 "tcp port 8080" 2>/dev/null | cut -d" " -f3-7 &  
sleep 1
nc -zv 127.0.0.1 8080 
sleep 1'
Connection to 127.0.0.1 8080 port [tcp/http-alt] succeeded!
127.0.0.1.38146 > 127.0.0.1.8080: Flags [S],
127.0.0.1.8080 > 127.0.0.1.38146: Flags [S.],
127.0.0.1.38146 > 127.0.0.1.8080: Flags [.],

Here is what each marked part does:

  1. 1--cap-add NET_RAW allows the container to read packets.
  2. 2tcpdump records packets. The option -i lo watches the loopback card, -c 3 stops after three packets, and "tcp port 8080" keeps only that traffic.
  3. 3cut -d" " -f3-7 keeps some columns of each line.
  4. 4nc -zv 127.0.0.1 8080 connects and closes at once. The option -z sends no data, and -v prints the result.

The client sends S, a SYN: are you there? The server answers S., a SYN-ACK: yes, and are you? The client sends ., an ACK: yes. Only now is the connection open, and data can follow. The port numbers on the client side change on every run.

SYNare you there?SYN-ACKyes, and are you?ACKconnected

SYN: the client asks whether anyone listens on this port.

What a firewall is

A firewall is a list of rules that decides which packets may pass. A rule can match a port, an address or a direction. It can accept the packet, drop it without any answer, or reject it with an answer. On Linux, a common tool for these rules is iptables. This rule drops every TCP packet that arrives for port 9002:

Shell
docker run --rm --cap-add NET_ADMIN alpine sh -c '
apk add -q iptables
iptables -A INPUT -p tcp --dport 9002 -j DROP 
iptables -S INPUT' 
-P INPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 9002 -j DROP

Here is what each marked part does:

  1. 1iptables -A INPUT -p tcp --dport 9002 -j DROP appends a rule (-A) to the INPUT chain, the packets for this machine. For TCP packets to port 9002, jump (-j) to DROP.
  2. 2iptables -S INPUT prints the chain as a list of rules.

The first line is the default, accept everything. The second line is our rule. The next example uses the same rule. A dropped packet gets no answer.

80accept: it passes9002drop: silence9002refusedreject: an answer comes back
A rule can let a packet pass, drop it without an answer, or reject it with an answer.

Two ways to fail

A connection can fail in two ways, and the machine reports them differently. In one container, we try a port where nothing listens, and then a port where a firewall rule drops every packet:

Which of the two will fail at once, and which will wait?

Shell
docker run --rm --cap-add NET_ADMIN alpine sh -c '
apk add -q netcat-openbsd iptables
time nc -zv 127.0.0.1 9001
iptables -A INPUT -p tcp --dport 9002 -j DROP
time nc -zv -w 3 127.0.0.1 9002' 
nc: connect to 127.0.0.1 port 9001 (tcp) failed: Connection refused
real	0m 0.00s
nc: connect to 127.0.0.1 port 9002 (tcp) timed out: Operation in progress
real	0m 3.00s

Here is what each marked part does:

  1. 1time prints how long the command took, and nc -w 3 gives up after 3 seconds.

On port 9001 nothing listens, so the kernel of the machine answers the SYN at once with a refusal, a packet called RST. A refusal means that something answered, so the packet arrived and the machine is alive. On port 9002 nobody answers. The SYN was dropped, so the client waits and tries again. A timeout tells us less. The cause can be a firewall rule, a machine that is off, or a wrong route from part 1.

refusedSYNRST: nobody here0.00 stimed outSYNsilence3 s with -w 3
Refused: the door answers at once. Timed out: nothing answers, and the client waits.

How long a connection waits

The -w 3 in the last command is our own deadline of three seconds. Without it, the wait is decided by the kernel. A client that sends a SYN and gets no answer sends it again, and the wait before each retry grows. Look at a connection in that state, and at the setting behind it:

Shell
docker run --rm --cap-add NET_ADMIN alpine sh -c '
apk add -q netcat-openbsd iptables iproute2
iptables -A INPUT -p tcp --dport 9002 -j DROP
(nc -zv -w 4 127.0.0.1 9002 >/dev/null 2>&1 &)
sleep 2
ss -tno state syn-sent 
sysctl net.ipv4.tcp_syn_retries' 
Recv-Q Send-Q Local Address:Port  Peer Address:Port
0      1          127.0.0.1:34068    127.0.0.1:9002 timer:(on,056ms,1)
net.ipv4.tcp_syn_retries = 6

Here is what each marked part does:

  1. 1ss -tno state syn-sent lists TCP connections that sent a SYN and wait, together with their timers.
  2. 2sysctl net.ipv4.tcp_syn_retries prints a setting of the kernel.

The state is SYN-SENT: the client has sent its SYN and waits. The timer field shows the retransmission timer. Its last number, 1, counts the retries so far. The tcp_syn_retries setting limits the retries to 6. The next command records every SYN that leaves, and -ttt prints the time since the previous packet:

Shell
docker run --rm --cap-add NET_ADMIN --cap-add NET_RAW alpine sh -c '
apk add -q netcat-openbsd iptables tcpdump
iptables -A INPUT -p tcp --dport 9002 -j DROP
tcpdump -nn -ttt -l -i lo -c 8 "tcp port 9002" 2>/dev/null | sed "s/^ *//" | cut -d" " -f1 &  
sleep 1
nc -zv -w 12 127.0.0.1 9002 2>&1 | head -1' 
00:00:00.000000
00:00:01.002229
00:00:01.027517
00:00:01.020542
00:00:01.027863
00:00:01.021893
00:00:02.046855
00:00:04.032813

Here is what each marked part does:

  1. 1-ttt prints the time since the previous packet, and -l prints each line at once.
  2. 2sed "s/^ *//" removes spaces at the start of each line.
  3. 3nc -w 12 gives up after 12 seconds.

The first retries come about one second apart. Then the wait grows to 2 seconds and then 4, and it keeps growing. On this kernel, the setting tcp_syn_linear_timeouts is 4, which keeps the first waits short. Other kernels can differ. To measure the whole wait, we run nc against the dropped port with no deadline:

Shell
docker run --rm --cap-add NET_ADMIN alpine sh -c '
apk add -q netcat-openbsd iptables
iptables -A INPUT -p tcp --dport 9002 -j DROP
time nc -zv 127.0.0.1 9002'
nc: connect to 127.0.0.1 port 9002 (tcp) failed: Operation timed out
real	2m 15.47s
about 1 s apart at firstthen the wait growsSYNgives up after about 2 minutes012345711135
The first retries leave about one second apart. Then the waits grow, and after about two minutes the client gives up.

TCP delivers the data in order, or it reports an error when it gives up. It does not say when it gives up. The total depends on the kernel settings: here it was 2 minutes and 15 seconds. That is long for a user and too long for a request inside a service.

After a connection is open, the wait can be longer. If the other side disappears without a word, Linux sends the data again, up to 15 times by default (tcp_retries2). The kernel documentation gives about 15 minutes for that.

Your program should set its own deadline, such as nc -w 3 here or curl --connect-timeout 3.

Key points

  • A port is a number that names one program on a machine. A program listens on a port to receive connections.
  • A TCP connection opens with three packets: SYN, SYN-ACK and ACK.
  • Connection refused comes at once. Something answered, usually the machine itself because nothing listens on that port.
  • Timed out means that nobody answered. A firewall, a machine that is off, or a wrong route can cause it.
  • With the default settings, a connection attempt to a silent address waits about two minutes on Linux.
  • TCP gives no time limit. Set a connect timeout in every client.

Next, in part 4: what travels inside an open connection, and why HTTP is only text.

New posts by email

One email when a post ships, about twice a month. Nothing else, and one click to leave.

Latest: Finding where a request breaks · RSS