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
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:
- MQTT, 26 bytes.
30— PUBLISH with QoS 0,18— remaining length 24,00 10— topic length 16, then the topic and 6 bytes of data. The MQTT header is 20 bytes out of 26: the topic costs more than the number. - TCP, 20 bytes. Ports
c0 00= 49152 and07 5b= 1883, sequence number 1000, acknowledgement 2000,50— a 20-byte header with no options,18— PSH and ACK flags, window 5840, checksumab 43. After sending, the next sequence number is 1026: the segment used 26 numbers (106.4). - IPv4, 20 bytes.
45— version 4 and a 20-byte header, total length00 42= 66, "don't fragment" flag, TTL 64, protocol 6 (TCP), checksumb7 28. - Ethernet, 14 bytes. The broker's MAC, our locally administered MAC (first byte 0x02, section 86.3), type 0x0800 — IPv4.
- FCS, 4 bytes. CRC-32 from the destination address to the end of the data, least significant byte first (105.2). The frame is 80 bytes without the FCS — longer than 60, no padding needed.
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:
- On CAN the address belongs to the message, not the node. The identifier says what is in the frame, not who it is for; there is no network layer at all.
- Modbus RTU mixes layers. The slave address and CRC are data-link, the function code and registers are application, yet they sit in one frame of one protocol. In Modbus TCP the data-link part is taken over by TCP/IP and the CRC goes away.
- USB is a tree with the host at the top. The host hands out addresses and polls devices; the "network" does not route, and the classes define the application meaning.
- UART without a protocol is only the first layer and half of the second layer. A byte arrived — that is all; where a message ends is decided by your code (16б, 115б).
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:
- Check the lower layer first. If ping does not pass, it is too early to look at the port and topic.
- Ping checks layers 1–3, not 4. A device can answer ping while TCP to the broker fails: closed port, firewall, no memory for a connection in lwIP.
- A capture settles everything. Wireshark on the PC or a switch mirror port shows every layer of a frame at once; a bad checksum in a capture taken on the sending PC is usually a trace of checksum offload in the network card, not an error.
- "Ping works, no data" after moving to another network is a common sign of NAT and a firewall on the path (86.5, 106.7), not of the firmware.
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
- Layers let you change one part without reworking the rest: moving from Ethernet to a modem does not touch the publishing code.
- OSI is seven layers for talking, TCP/IP is four for working; layers five and six in a device are part of the application.
- In an STM32F407 the first layer is the PHY, the second layer the MAC on the chip plus the ETH driver, the third and fourth layers are lwIP, above that — your code.
- A 6-byte publish: MQTT 26, TCP 46, IPv4 66, frame 84, on the wire 104 bytes; 7.14 % of the frame is useful.
- In a 1518-byte frame the TCP segment is 1460 bytes, MQTT data with a 16-byte topic is 1439, 94.80 %; buffering and sending in batches pays.
- Our own IP checksum
b728, TCPab43and FCS77 73 02 09are confirmed by tshark; a corrupted data bit is caught by the FCS and the TCP checksum, but not by the IP checksum. - CAN, Modbus RTU, USB and UART fit the model only partly: often there are only the first, second and application layers.
- Faults are searched for bottom-up: link, ARP, ping, port, protocol.
Next: section 86в "TCP and UDP in detail: handshake, ports, window, retransmissions, closing — and what it means for a microcontroller (lwIP)".