Embedded HandbookApps
All sections › X. Design, networks and IoT
STM32F407 · level intermediate · 12 min read
Open in the interactive handbook

86б. The OSI model and the TCP/IP stack: what works at which layer in a device

Section 86 covered network types and addresses, section 86а covered IP addressing: masks and subnets. This section is the map onto which all the network sections of the handbook fit: the seven layers of the OSI model, the four layers of the TCP/IP stack, and the answer to the question "which part is done by the PHY, which by the MAC on the chip, which by the driver, which by lwIP and which by my application".

Sources: section 105 — the Ethernet frame, IPv4 and ARP byte by byte; 106 — TCP and UDP; 106а–106в — Ethernet on the F407, a packet as the microcontroller sees it, and lwIP; 198и — an MQTT client. The headers themselves are taken apart field by field there; here they are put together into one frame. The frame is built by our own Python code and checked independently: Wireshark (tshark 4.0) decoded it and confirmed all three checksums.

What it is called in the documentation

Original Meaning
OSI reference model Open Systems Interconnection reference model
layer, protocol stack layer, protocol stack
PDU (protocol data unit) data unit of a layer
encapsulation / decapsulation wrapping / unwrapping
header, trailer, payload header, trailer, useful data
frame, packet, segment, datagram frame, packet, segment, datagram
physical / data link / network / transport layer the lower four layers
session / presentation / application layer the upper three layers
link layer, internet layer (TCP/IP) network access layer, internet layer
pseudo-header pseudo-header
checksum offload checksums computed in hardware

In plain words. A letter goes into an envelope, the envelope into a sack, the sack into a truck. The postman does not care what the letter says, and the driver does not care what is on the envelope. A network works the same way: each layer adds its own "wrapping" and reads only that. So you can swap the truck for a train without rewriting the letters.


86б.1 Why layers, and what each of the seven does

Layers let you change one part without reworking the rest. A device that sends MQTT over Ethernet can move to Wi-Fi or a cellular modem (section 106г), and the publishing code does not change: the two lower layers changed. Switch the broker — the network-layer address changes, the Ethernet frames stay the same. Each layer gives the layer above one service and does not know how it is done below.

# Layer What it does Data unit Address In an STM32F407 device Who does it
1 physical bits into a signal on the wire bit, symbol none twisted pair, transformer, PHY LAN8742A (106а) hardware: PHY
2 data link a frame between neighbours, integrity check frame MAC Ethernet frame, FCS (105.1–105.2) MAC on the chip + ETH driver (106а)
3 network delivery through routers packet IP IPv4, ARP, ICMP (105.4–105.7) lwIP: ip4, etharp (106в)
4 transport a stream or datagrams between programs segment (TCP), datagram (UDP) port TCP to the broker, UDP for DNS (106) lwIP: tcp, udp
5 session start, continuation and end of a conversation — session, client id MQTT session, reconnection (198и) application
6 presentation encoding and encryption — — JSON, CBOR (115г), TLS application, library
7 application the meaning of the exchange message topic, URL, register MQTT, HTTP (107, 142), Modbus TCP (89.4) application

The hardware/software boundary in a device runs through the middle of the second layer. The PHY turns bits into a signal and back; the F407 MAC builds the frame: adds padding and the FCS on transmit (105.1) and, if asked, computes the IP and TCP checksums itself (106б.6). The HAL ETH driver runs the ring of DMA descriptors — still the second layer, but already software. The Ethernet header, ARP and everything above are written by lwIP; above TCP it is your code.


86б.2 The four TCP/IP layers, and where the fifth and sixth went

The OSI model is a reference for talking. The working Internet stack is simpler: four layers from RFC 1122.

TCP/IP OSI Example in a device Section
network access 1 and 2 Ethernet, Wi-Fi, cellular modem 105, 106а, 106г
internet 3 IPv4, ICMP, ARP (between 2 and 3) 105, 106б
transport 4 TCP, UDP 106
application 5, 6, 7 MQTT, HTTP, DNS, DHCP, TLS 107, 142, 198и

Layers five and six do not live separately in a device. An MQTT session is a flag in the CONNECT packet plus reconnection logic in the same program that publishes the data. Encoding into JSON is a function of the same application. TLS formally sits between the transport and application layers, but in firmware it is a library the application calls instead of a bare socket. There is no separate "session layer" code in lwIP — which is why the TCP/IP stack merges them into one application layer.

ARP sits on the seam: its frame is data-link (type 0x0806), but it answers a network-layer question, "what MAC does this IP have" (105.6). There are plenty of such cross-layer protocols, and the model honestly does not describe them.


86б.3 Encapsulation: one MQTT publish byte by byte

Header nesting of one MQTT publish: a preamble of 8 and a gap of 12 bytes around an 84-byte Ethernet frame; inside it a 14-byte Ethernet header, a 4-byte FCS and a 66-byte IPv4 packet; inside the packet a 20-byte IPv4 header and a 46-byte TCP segment; inside the segment a 20-byte TCP header and a 26-byte MQTT message; inside the message a 20-byte MQTT header and 6 bytes of data; on the right, who handles each layer

A device at 192.168.1.50 publishes the string t=23.1 to the topic lab/f407-01/meas on the broker 192.168.1.10, port 1883, without acknowledgement (QoS 0). Each layer puts the data of the layer above into its data field and adds its own header. The frame is built by the bench script calc86b.py — here it is, layer by layer:

eth   14  02 00 00 00 00 01 02 80 e1 00 00 86 08 00
ip    20  45 00 00 42 00 01 40 00 40 06 b7 28 c0 a8 01 32 c0 a8 01 0a
tcp   20  c0 00 07 5b 00 00 03 e8 00 00 07 d0 50 18 16 d0 ab 43 00 00
mqtt  26  30 18 00 10 6c 61 62 2f 66 34 30 37 2d 30 31 2f 6d 65 61 73 74 3d 32 33 2e 31
fcs    4  77 73 02 09

What each line holds:

The IP and TCP checksums are computed by one function — the Internet checksum. For TCP an imaginary pseudo-header is placed in front of the header: the IP addresses, the protocol number and the length. That is how the transport layer checks that the segment arrived at the right address — by peeking one layer down:

def csum16(data):
    """Контрольная сумма Интернета (RFC 1071): сумма 16-битных слов в обратном коде."""
    if len(data) % 2:
        data += b"\x00"
    s = 0
    for i in range(0, len(data), 2):
        s += (data[i] << 8) | data[i + 1]
        s = (s & 0xFFFF) + (s >> 16)
    return ~s & 0xFFFF
pseudo = SRC_IP + DST_IP + struct.pack("!BBH", 0, 6, len(tcp0) + len(mqtt))
tcp_cs = csum16(pseudo + tcp0 + mqtt)

How it was checked. On the example from RFC 1071 the checksum function gave the sum ddf2 and the checksum 220d, as in the document; a second, differently built method (remainder modulo 0xFFFF) gave the same IP and TCP checksums. Recomputing over a header together with its finished checksum gives 0000 — that is how the receiver checks. Our own CRC-32 on the string "123456789" gave cbf43926, matched zlib over the whole frame, and the CRC of the frame together with its FCS gives the constant residue debb20e3. Scapy is not in the bench images, so tshark is the independent judge: it decoded the frame as Ethernet → IPv4 → TCP → MQTT (type 3, QoS 0, length 24, topic lab/f407-01/meas) and marked the FCS, the IP checksum and the TCP checksum as good. In a copy of the frame with one corrupted data bit (23.1 → 23.0) tshark marked the FCS and the TCP checksum as bad and the IP checksum as good: the IP header does not protect the data.


86б.4 How many useful bytes out of 1518

What Bytes Share of the 6 data bytes
data t=23.1 6 —
MQTT message 26 —
TCP segment 46 —
IPv4 packet 66 —
Ethernet frame with FCS 84 7.14 %
on the wire with preamble and gap 104 5.77 %

A small measurement carries 78 bytes of headers in the frame and 98 bytes on the wire. At 100 Mbit/s such a frame occupies the line for 8.32 µs, and the line can carry 120 192 such frames per second — the network is not the bottleneck for the device; the useful share is.

The longest frame is 1518 bytes: 18 bytes of Ethernet and 1500 bytes of data (the MTU). Minus 20 bytes of IPv4 and 20 bytes of TCP leaves a 1460-byte segment — the MSS from section 106.2. With the same topic the MQTT header takes 21 bytes (the remaining length now needs two bytes), and 1439 bytes of data fit — 94.80 % of the frame, 93.56 % of the line; the overhead is 79 bytes. If the stack enables TCP timestamps (10 bytes plus 2 bytes of padding, as Linux sends — section 106.2), the segment is 1448 bytes, the data 1427, 94.01 % of the frame.

The practical conclusion: buffering measurements and sending them in a batch pays off. Six bytes in a frame is 7.14 % useful, a full frame is 94.80 %. The price is latency and buffer memory (section 106в.3).


86б.5 Where the OSI model fits poorly

The model was invented for routed networks. Field buses and on-board interfaces are simpler, and the honest answer to "which layers are here" is often "the first, the second, and straight to the seventh".

Bus 1 physical 2 data link 3–4 7 application Section
UART TTL levels, RS-232 only a byte with start and stop; frame, address and check are up to the protocol none own protocol, AT commands 16, 106г
RS-485 + Modbus RTU differential pair, terminators frame by silence, slave address, CRC-16 — all inside Modbus none Modbus functions and registers 16а, 198в, 89.4
CAN differential pair, dominant bit frame, arbitration, CRC, acknowledgement — in the controller none (long messages — ISO-TP, 19в) CANopen, J1939, UDS 19, 19б, 19и
USB D+/D− pair, NRZI packets, CRC, handshakes — in the USB controller device address and endpoint — no routing CDC, HID, MSC classes 20, 20в

How this differs from Ethernet:

Here the model is useful as a question, not as an answer: "who on this bus is responsible for integrity, who for addressing, who for retries". If nobody — your protocol is.


86б.6 Troubleshooting from the bottom up

"The device does not send data" is a seventh-layer complaint. The search starts at the bottom: each step narrows it down to one layer. The commands are for a PC on the same subnet.

Step Layer What to check PC command Where in the device
1 1 is the link LED on, is it the right cable — link bit in the PHY BSR register over MDIO (106а.3)
2 2 does the PC see the device's MAC arp -a (Windows), ip neigh (Linux) lwIP ARP replies, etharp counters (106в)
3 3 does the device answer ping, are gateway and mask right ping 192.168.1.50, tracert / traceroute ICMP in lwIP, address and mask (86а, 105.5)
4 4 is the broker port open Test-NetConnection 192.168.1.10 -Port 1883 (PowerShell), nc -vz 192.168.1.10 1883 tcp_connect returned an error or SYN retries (106.6)
5 7 does the broker accept the connection and data mosquitto_sub -h 192.168.1.10 -t 'lab/#' -v CONNACK return code, topic and permissions (198и)

Rules that save time:


86б.7 Pitfalls

"MQTT runs over TCP, so it will be delivered." TCP guarantees order and integrity only while the connection is alive. Once it drops, unacknowledged bytes are lost, and only the application can find out. Hence QoS 1 and publish retries at the seventh layer (198и).

The IP checksum is good but the data is corrupted. The IPv4 header checksum protects only the header: in this section's experiment with one corrupted data bit tshark marked the IP checksum as good. The data is protected by the TCP or UDP checksum and the frame FCS.

Checksum offload is on and you see zeros. With hardware checksums the fields in memory are zeros and the MAC inserts the sum on the way out (106б.6). In a capture on the device itself this is not an error; on the wire the checksum is already right.

"Layer 2 is the switch, so the MAC does not matter." Every frame on a local network travels by MAC. Two devices with the same MAC — and one of them disappears, even though their IP addresses differ (86.3).

A message longer than one frame. TCP is a stream: a 3 KB publish leaves as several segments, and the receiver gets it in pieces. Message boundaries are kept by the application protocol (the MQTT remaining length), not by TCP.

Debugging top-down. An hour is spent looking for an error in the MQTT topic while the cable is plugged into the wrong port. The order is bottom-up: link, ARP, ping, port, protocol.


86б.8 Summary

Next: section 86в "TCP and UDP in detail: handshake, ports, window, retransmissions, closing — and what it means for a microcontroller (lwIP)".

Open in the interactive handbook