08 — MBAP HEADER & TRANSACTIONS
How the master matches responses to overlapping requests.
Estimated 6 minutes.
Why the envelope matters.
A Modbus TCP master often has multiple requests in flight at once. The MBAP header is the bookkeeping that lets it tell the responses apart, even when the slave answers out of order.
Two requests, two responses.
Transaction IDs are copied unchanged. Order on the wire does not matter.
Transaction ID — the master's counter.
The master picks any 16-bit number for the TID. Most implementations just increment a counter and let it wrap. The slave copies the TID into the response unchanged.
Protocol ID — always 0.
PID is 2 bytes, always 0x0000 for vanilla Modbus. Reserved for future variants that never shipped. Send 0; reject anything else as malformed.
Length — bytes that follow.
The length field counts the bytes that come AFTER the length field itself: unit ID (1) + function code (1) + data (0–252). Slave uses it to know how much to read from the TCP stream.
All four fields in one glance.
TID · PID · LEN · UID. Seven bytes, every time.
Transaction tracker.
Outgoing requests stream on the left with auto-incrementing TIDs. Incoming responses arrive out of order on the right. Drag each response to its matching request.
Unit ID — mostly for gateways.
Native Modbus TCP slaves often ignore the unit ID (or expect 1). Where it matters: gateways that bridge a single TCP endpoint to several serial slaves. Each serial slave has its own unit ID; the gateway routes by that byte.
Talk to slave #3 behind a gateway.
A gateway lives at IP 10.0.0.5. Behind it are 4 serial slaves with unit IDs 1, 2, 3, 4. How do you send a request to slave #3?
- Different IP for each slave
- Same IP 10.0.0.5, unit ID = 3 in the MBAP
- Different TCP port for each slave
Three responses come back out of order.
Master fires three requests fast. Three responses come back, shuffled. How does the master match them?
- It checks the order they arrived
- It reads the TID in each response and finds the matching pending request
- It opens a new TCP connection per request
You can decode any MBAP header.
- TID — master's counter, slave copies it back.
- PID — always 0.
- Length — bytes after the length field.
- Unit ID — picks a destination behind a gateway.
Lesson 08 complete.
- You understand why the TID exists and how it makes overlapping requests safe.
- You can explain when the unit ID matters and when it does not.
- You can read any 7-byte MBAP off the wire.