86в. TCP and UDP in detail: handshake, ports, window, retransmissions, closing — and what it means for a microcontroller (lwIP)
Section 86а covered IP addresses, section 86б covered layers and the nesting of headers. This section takes the whole transport layer, not field by field but by its behaviour in time: how a connection opens, how data is cut into segments, what happens on a loss, who waits after closing and how UDP differs in practice. And for every point — what follows from it for a device running lwIP with its tens of kilobytes of RAM.
Sources: section 106 — TCP and UDP headers, numbers, window and NAT; 106а — Ethernet on the F407; 106б — a packet byte by byte; 106в — lwIP: buffers, pools and settings; 198ж — a UDP sensor; 78 — sockets. All the numbers below come from one experiment: an exchange over the loopback interface in a Linux container, recorded to pcap, decoded by our own Python code and, independently, by Wireshark (tshark 4.0). The kernel parameters are set to match lwIP: no timestamps, no window scaling, no SACK, MSS 1460.
What it is called in the documentation
Original Meaning port, socket port, socket (address + port) three-way handshake three-way handshake sequence / acknowledgment number sequence number / acknowledgment number MSS (maximum segment size) largest amount of data in one segment receive window, zero window receive window, zero window zero window probe zero window probe retransmission, RTO retransmission, retransmission timeout exponential backoff doubling of the timeout FIN, RST polite close, reset TIME_WAIT waiting after the close datagram datagram ICMP port unreachable ICMP "port unreachable" In plain words. UDP is a postcard: write the address, drop it in the box, and you never know whether it arrived. TCP is a phone call: first get through, then talk with "got it?" checks, and say goodbye at the end. The call is more reliable, but for a short "23 degrees" the postcard is nine times cheaper.
86в.1 Ports: who inside the device gets the data
The IP address brings a packet to the device, the port brings it to a program inside it. A port is a number from 0 to 65535 in the TCP or UDP header. A TCP connection is uniquely defined by four numbers: the address and port of our side, the address and port of the peer. That is why one server on port 5000 can hold many clients: each has its own port.
In the experiment the client — the "device" — sits on port 49152, the server listens on 5000. Usually the client port is chosen by the stack from the ephemeral range (in lwIP it starts at 49152); here it is fixed so that the recording repeats.
For a microcontroller a port is also memory. Every listening TCP port in lwIP is an entry from the MEMP_NUM_TCP_PCB_LISTEN pool, every connection is an entry from MEMP_NUM_TCP_PCB (5 by default, section 106в.3). The sixth client of the device's web server is refused, even though the port is open.
86в.2 The handshake and the MSS
Here are all segments of the experiment except the window experiment
(86в.4), as decoded by our own code calc86c.py: the seq and ack numbers
are relative, counted from each side's initial number, as Wireshark shows
them.
1 TCP 5000 c>s S seq 0 ack 0 win 64240 len 0 MSS 1460
2 TCP 5000 s>c SA seq 0 ack 1 win 64240 len 0 MSS 1460
3 TCP 5000 c>s A seq 1 ack 1 win 64240 len 0
4 TCP 5000 c>s A seq 1 ack 1 win 64240 len 1460
5 TCP 5000 s>c A seq 1 ack 1461 win 65535 len 0
6 TCP 5000 c>s A seq 1461 ack 1 win 64240 len 1460
7 TCP 5000 s>c A seq 1 ack 2921 win 65535 len 0
8 TCP 5000 c>s AP seq 2921 ack 1 win 64240 len 80
9 TCP 5000 s>c A seq 1 ack 3001 win 65535 len 0
10 TCP 5000 s>c AP seq 1 ack 3001 win 65535 len 8
11 TCP 5000 c>s A seq 3001 ack 9 win 64232 len 0
12 TCP 5000 c>s AP seq 3001 ack 9 win 64232 len 7
13 TCP 5000 s>c A seq 9 ack 3008 win 65535 len 0
14 TCP 5000 c>s AF seq 3008 ack 9 win 64232 len 0
15 TCP 5000 s>c A seq 9 ack 3009 win 65535 len 0
16 TCP 5000 s>c AF seq 9 ack 3009 win 65535 len 0
17 TCP 5000 c>s A seq 3009 ack 10 win 64232 len 0
18 TCP 5001 c>s S seq 0 ack 0 win 64240 len 0 MSS 1460
19 TCP 5001 s>c AR seq 1 ack 1 win 0 len 0
20 UDP 5002 c>s len 14 (data 6)
21 UDP 5003 c>s len 14 (data 6)
22 ICMP type 3 code 3, 42 bytes
The first three lines are the handshake: S, SA, A. The client offers its initial number, the server acknowledges it (ack 1 — "I am waiting for byte number 1") and offers its own, the client acknowledges. The SYN flag, like FIN, takes one number, so the data starts at seq 1. The SYN header is 24 bytes: 20 mandatory bytes and 4 bytes of the MSS option.
The MSS is how much data a side is ready to accept in one segment. Both sides announced 1460: that is the 1500-byte Ethernet MTU minus 20 bytes of IPv4 and 20 bytes of TCP (86б.4). The sender takes the smaller of the two. In lwIP the default is TCP_MSS = 536 — with this value the device itself announces 536, and the peer has to cut the stream finer, with three times as many segments and headers. For Ethernet set 1460 (106в.3).
The handshake costs time: one round trip before the first byte of data. A device that opens a new connection for every measurement pays this round trip every time.
86в.3 The stream, segments and acknowledgments
The client handed over 3000 bytes in one sendall call. They went onto
the network as three segments — 1460, 1460 and 80 (lines 4, 6, 8): TCP is
a byte stream, there are no call boundaries in it. The last segment carries
the PSH flag — "hand it to the application right away". The server
acknowledged each one: ack 1461, 2921, 3001 — the number of the next
expected byte, not the number of a segment. The server's reply is 8 bytes
OK 3000\n (line 10); the client acknowledged it with ack 9.
For the receiver the main rule follows from this: read as much as has
arrived and assemble the message by its own markers. The server in the
experiment read in a loop until it had 3000. On lwIP it is the same: the
recv callback in the raw API gets a pbuf chain of arbitrary length, and
one message may arrive in two calls, and two messages in one (106в.5).
86в.4 The window: how much can be sent without acknowledgment
The window (win) is how many bytes the receiver is still ready to take. The sender does not send more than the window without an acknowledgment. Linux announced 64240 and 65535 — without window scaling it cannot be more than 65535. For the second experiment the receiver was given a buffer of 2920 bytes and was not allowed to read for 1 s, while the client tried to send 20000 bytes.
In the SYN+ACK the receiver announced a window of 2920. After the first segment of 1460 bytes the window became 1460, after the second — 0. The sender stopped and began sending zero window probes — segments without data with a number one less than expected (seq 2920 when 2921 is expected): "are you still alive, has the window opened?". Wireshark marks them as Keep-Alive: they look the same. In one second 2 probes went out, the receiver answered twice with window 0. As soon as the application read the buffer, the window opened to 2920, and all 20000 bytes arrived in 14 segments.
This is a normal mode for lwIP, not a failure. The device's window is
TCP_WND, in the configuration from 106в it is 2920 bytes, and until the
application releases the pbuf and calls tcp_recved, the window does not
open. The speed is then limited by the window and the round-trip time: no
more than one window goes out per round trip.
| Window | Round trip 10 ms | Speed limit |
|---|---|---|
| 2920 bytes (2 · MSS) | 10 ms | 2336 kbit/s |
| 5840 bytes (4 · MSS) | 10 ms | 4672 kbit/s |
Two conclusions follow. Want it faster — enlarge the window, which means more RAM for pbufs. And slow processing on the device honestly slows down the sender: TCP will not lose data, but the peer will wait.
86в.5 Loss and retransmission
The third experiment: the loopback is set to lose all packets (netem,
100 %), the client sent 7 bytes t=23.1\n, and after one second the loss
was removed. The experiment itself:
sh("tc qdisc add dev lo root netem loss 100%") # всё, что уходит в lo, пропадает
log.append("lost_t0=%.6f" % time.time())
cli.sendall(b"t=23.1\n")
time.sleep(1.0)
r1 = tcp_info(cli)
sh("tc qdisc del dev lo root")
got = con.recv(64)
After one second the client kernel had counted 2 retransmissions, and the retransmission timeout (RTO) had grown to 800 ms. The RTO doubles after each failure: 200, 400, 800 ms. The segment got through on the third retransmission, ≈1.5 s after sending, with the same seq 3001 (line 12). There is only one copy of it in the recording: the copies eaten by the loss never reached the capture point. The server application received the whole string and noticed nothing.
lwIP behaves the same way but with a different step: the TCP timer ticks
every 500 ms, the first RTO in the sources is 3 s, and after TCP_MAXRTX
retransmissions (12 by default) the connection is dropped with an error.
So the device learns about a vanished broker not at once but after tens of
seconds, and all that time the data sits in TCP_SND_BUF. If measurements
must be fresh rather than complete, it is sensible to limit the queue
yourself and check whether the stack accepted the bytes (tcp_write
returned an error — no room).
86в.6 Closing, TIME_WAIT and reset
Closing takes 4 segments (lines 14–17): the client's FIN, ACK, the server's FIN, ACK. Each side closes its own half of the stream. The one that closed first — the client in the experiment — stays in the TIME_WAIT state: after the experiment the kernel showed state 06 for port 49152, which is TIME_WAIT. It waits so that a late segment of the old connection does not get into a new one with the same ports. In Linux the wait is 60 s, in lwIP it is 2 · TCP_MSL, 120 s by default.
For a device this is memory: a connection entry in TIME_WAIT occupies a place in the pool until the time runs out. When short of entries lwIP takes one from the oldest TIME_WAIT, but it is better if the peer closes first: then the wait stays on its side, where there is plenty of memory.
A reset (RST) is a rough close. A SYN to port 5001, where nobody listens,
got RST+ACK with ack 1 in reply (lines 18–19), and the client's connect
ended with a ConnectionRefusedError. An RST also arrives if the peer
restarted and does not know the old connection: lwIP reports this through
the tcp_err error callback, and by that moment the connection entry has
already been freed — it must not be touched.
86в.7 UDP: cheap, but you do everything yourself
The datagram with t=23.1 to port 5002 is a single line 20: 8 bytes of
UDP header and 6 bytes of data, length 14. No handshake, no acknowledgment,
no closing. The IPv4 packet is 34 bytes, the Ethernet frame with FCS is
64 bytes (the minimum).
The same datagram to the closed port 5003 (line 21) caused an ICMP reply of type 3 code 3 — "port unreachable" (line 22, 42 bytes: the ICMP header and the beginning of the rejected packet). The send itself went through without an error, and the client got a ConnectionRefusedError only on the next send: UDP reports non-delivery after the fact, and not always — ICMP may be filtered.
| The same 6 bytes | Frames | Bytes in frames |
|---|---|---|
| UDP | 1 | 64 |
| TCP: open, send, acknowledge, close | 9 | 576 |
A TCP session for one measurement is 9.0 times more expensive in bytes and
nine times in frames. Hence the practice: rare short measurements — UDP with
your own number and, if needed, your own acknowledgment (198ж); a stream or
important data — one long-lived TCP connection that is not closed after
every send. UDP in lwIP has no window and no queue: udp_sendto hands the
pbuf over at once, and if ARP does not yet know the peer's MAC, the first
datagram may be lost (105.6).
86в.8 Pitfalls
One send — one recv. It does not work that way: the 3000 bytes in
the experiment arrived as three segments. Message boundaries are the
application's business: a length at the start or a delimiter.
The default TCP_MSS. 536 instead of 1460 — three times as many segments and acknowledgments for the same stream. The first thing to fix in lwipopts.h for Ethernet.
The window does not open. tcp_recved was forgotten or a pbuf is held
— the window shrinks to zero, the peer sends probes and waits. From the
outside it looks like "the device hung on receive".
A new connection for every measurement. Nine frames instead of two and a TIME_WAIT for every close; the connection pool runs out faster than it seems.
The connection is "alive" but the peer is gone. While the device sends nothing, it will not learn about a break: TCP is silent when there is nothing to acknowledge. TCP keepalive or your own ping at the application layer is needed (MQTT keepalive, 198и).
A retransmission is not instant. A loss costs hundreds of milliseconds on a PC and seconds on lwIP. An application watchdog timeout shorter than the RTO — and the device breaks a connection that was about to recover.
86в.9 Summary
- The port selects a program inside the device; a connection is defined by four numbers, and each one is an entry in the lwIP pool (5 by default).
- The handshake is 3 segments, the close is 4; SYN and FIN take one number each; MSS 1460 for Ethernet, not the default 536.
- 3000 bytes went out as segments of 1460, 1460 and 80: TCP is a stream, there are no boundaries.
- A 2920-byte window without reading shrank to 0 in two segments; the sender sent probes and waited; the speed limit is one window per round trip: 2336 kbit/s with 2920 bytes and 10 ms.
- The lost segment got through on the third retransmission after ≈1.5 s, RTO 200, 400, 800 ms; lwIP has a 500 ms step and up to 12 retransmissions.
- TIME_WAIT stays with the one who closed first; let it be the peer.
- A closed port: TCP — RST+ACK, UDP — ICMP 3/3 after the fact.
- 6 bytes over UDP are 64 bytes in a frame, over TCP with opening and closing — 576 bytes and 9 frames.
Next: section 87 "Virtualization, clouds, containers".