14  Packet Anatomy

In 60 Seconds

Packet anatomy explains how every transmitted message is split into control information, application data, and an integrity check. Once you can spot the header, payload, and trailer, you can read protocol diagrams, estimate overhead, and debug real captures with confidence.

14.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Dissect packet anatomy: Identify and label headers, payloads, and trailers in real network packets
  • Interpret protocol specifications: Decode frame format diagrams and field layouts from datasheets and RFCs
  • Distinguish packet components: Classify control information versus application data within captured frames
  • Calculate overhead ratios: Compute the efficiency of different packet formats and assess their impact on bandwidth and battery life
  • Diagnose network issues: Apply packet structure knowledge to troubleshoot connectivity problems using tools like Wireshark
  • Compare error detection methods: Evaluate when to use checksums, CRC-16, CRC-32, or message integrity codes for different IoT scenarios
Most Valuable Understanding (MVU)

Every network packet has exactly three parts: Header (where to go), Payload (what to send), and Trailer (did it arrive correctly).

This is the single most important concept in network communication. Whether you’re working with LoRaWAN, MQTT, CoAP, Bluetooth, or any other protocol, you will always find these three components. Master this structure, and you can decode any protocol specification.

Remember: Header = Routing Information, Payload = Your Data, Trailer = Error Check

Prerequisites (Read These First):

Companion Chapters (Packet Structure Series):

Fundamentals (Core Concepts):

Protocol-Specific Packet Structures:

  • MQTT - MQTT fixed/variable headers, QoS, and packet types
  • CoAP - CoAP 4-byte header and message format
  • LoRaWAN - LoRa MAC header (MHDR), DevAddr, FCnt, MIC

14.2 Prerequisites

Before this chapter, you should understand:


Hey there, future network engineer! Let’s learn about packets with the Sensor Squad!

Sammy the Sensor has an important temperature reading (22.5 degrees Celsius) that needs to get to Cloudy the Cloud. But how does Sammy send this message across the network? By packing it into a packet!

Think of it like mailing a birthday present:

  1. The Present (Payload) - The actual gift you want to send (Sammy’s temperature reading: 22.5C)
  2. The Box and Address Label (Header) - Tells the postal service WHERE to send it (to Cloudy’s address) and WHO sent it (from Sammy)
  3. The Tape Seal (Trailer) - Proves the box wasn’t opened or damaged during shipping (a special number that checks if the data is correct)

The Sensor Squad Adventure:

  • Sammy measures: “It’s 22.5 degrees!”
  • Sammy puts the number in a packet with his address and Cloudy’s address
  • Nina the Network carries the packet through the internet
  • Cloudy checks the seal (trailer) - “Looks good! The data wasn’t damaged!”
  • Cloudy opens the payload - “Got it! 22.5 degrees!”

Fun Fact: Even tiny sensors like Sammy send THOUSANDS of packets every day. Each one has a header, payload, and trailer - just like thousands of little letters being mailed!

Try This: Next time you send a text message, remember that your phone wraps your words in a packet with an address (header) and a seal (trailer) before sending it!


14.3 For Beginners

Analogy: Packets are like Postal Letters

Just like a letter has a standard structure, network packets have a predictable format:

  • Header (envelope) - return address, destination address, and stamp tell the postal system where to send the letter and who sent it.
  • Payload (letter body) - the actual message you write to your friend.
  • Trailer (signature) - a final check such as a signature that lets the recipient verify it really came from you.

Network Packet:

The same idea appears in networking:


  • Header What it contains: source/destination, length, type, sequence number, flags Typical size: 10-40 bytes
  • Payload What it contains: sensor reading, command, JSON message, or even another packet Typical size: variable
  • Trailer What it contains: checksum/CRC, end marker, optional padding Typical size: 2-4 bytes

Why does this structure exist?

  1. Routing: Headers tell devices where to send the packet
  2. Integrity: Trailers verify data wasn’t corrupted
  3. Multiplexing: Multiple conversations share the same wire
  4. Reassembly: Large messages split into smaller packets

Key Terms:

  • Packet: complete unit of data for transmission.
  • Frame: packet at the data link layer, including physical markers.
  • Header: metadata at the beginning such as addresses, length, and type.
  • Payload: the actual data being transmitted.
  • Trailer: metadata at the end for error checking.
  • Checksum: simple error detection value.
  • CRC: cyclic redundancy check with stronger error detection.
  • MTU: maximum transmission unit, the largest packet size allowed.

Real-World Example: LoRaWAN Temperature Sensor Packet

Let’s dissect a real LoRaWAN packet from a temperature sensor deployed in a smart building. This packet was captured using a LoRaWAN gateway during an actual transmission:

Raw Packet (Hexadecimal):

40 3A 2B 1C 0D 80 02 00 01 C8 49 E2 F4 A3 B7 82 1F

Breaking it down:

  • MHDR Bytes: 1 Hex value: 40 Decoded value: Message Type: Unconfirmed Data Up Purpose: indicates packet type and direction.
  • DevAddr Bytes: 4 Hex value: 3A 2B 1C 0D Decoded value: Device Address: 0x0D1C2B3A Purpose: unique 32-bit device identifier.
  • FCtrl Bytes: 1 Hex value: 80 Decoded value: Frame Control: ADR enabled Purpose: controls adaptive data rate and options.
  • FCnt Bytes: 2 Hex value: 02 00 Decoded value: Frame Counter: 2 Purpose: prevents replay attacks by incrementing each transmission.
  • FPort Bytes: 1 Hex value: 01 Decoded value: Port 1 Purpose: application port number.
  • Payload Bytes: 2 Hex value: C8 49 Decoded value: Temperature: 22.5C Purpose: actual sensor data. The encoding is application-specific and decoded by the device codec.
  • MIC Bytes: 4 Hex value: E2 F4 A3 B7 Decoded value: Message Integrity Code Purpose: CRC-like authentication tag.
  • Extra Bytes: 2 Hex value: 82 1F Decoded value: Gateway metadata Purpose: RSSI and SNR added by the gateway after reception.

Total on-air LoRaWAN frame: 15 bytes (9 bytes header: MHDR + DevAddr + FCtrl + FCnt + FPort, plus 2 bytes payload, plus 4 bytes MIC) = 87% overhead for just 2 bytes of temperature data! (The 2 gateway metadata bytes are added after reception, not transmitted.)

Key Insights:

  • DevAddr routes the packet to the correct application server
  • FCnt prevents attackers from replaying old packets
  • MIC uses AES-128-CMAC to verify packet authenticity and integrity
  • Small payload (2 bytes) means high overhead ratio, but LoRaWAN optimizes for range (10+ km) and battery life (10+ years)
  • Gateway adds metadata (RSSI, SNR) to help with diagnostics

Why is this structure important?

  • Parsing this packet requires reading the LoRaWAN specification to understand each field
  • Frame counter must increment or the network server rejects the packet (anti-replay protection)
  • Payload encoding (C8 49 -> 22.5C) is application-specific and decoded by the device’s Codec, not part of the LoRaWAN spec
  • Understanding packet structure helps debug connectivity issues with tools like Wireshark or TTN Console

Key Insights:

For a LoRaWAN sensor with current settings:

$ = % $

  • Overhead: \({headerBytes} / (\){headerBytes} + \({payloadBytes}) × 100% = **\){overheadRatio}%**
  • Daily transmission: × \({totalPacketSize} bytes = **\){dailyBytes.toLocaleString()} bytes/day**
  • Annual network total: MB/year for sensors

Trade-off: Larger payloads reduce overhead percentage but require coordinating measurement timing. The graph shows how efficiency improves with payload size—doubling from 2 to 4 bytes drops overhead from ~88% to ~79%.


14.4 Packet Anatomy Fundamentals

Time: ~8 min | Difficulty: Foundational | Unit: P02.C02.U01

14.4.1 The Three Parts of Every Packet

Every network packet, regardless of protocol, contains these fundamental components:

1. Header (Control Information)

  • Purpose: Routing, identification, and control
  • Contains: Source/destination addresses, packet length, protocol type, sequence numbers, flags
  • Size: Typically 10-40 bytes depending on protocol

2. Payload (The Actual Data)

  • Purpose: Carry the message or data being transmitted
  • Contains: Sensor readings, commands, JSON data, or another encapsulated packet
  • Size: Variable, constrained by Maximum Transmission Unit (MTU)

3. Trailer (Error Detection)

  • Purpose: Verify data integrity
  • Contains: Checksum or CRC value, optional end-of-frame marker
  • Size: Typically 2-4 bytes

14.4.2 Packet Structure Diagram

Packet anatomy overview showing a transmitted frame split into header, payload, and trailer, with example fields, typical byte counts, and the role of each region in routing, carrying sensor data, and integrity checking.

This overview shows how one transmitted frame is assembled: the header tells the network how to handle the message, the payload carries the useful application data, and the trailer lets the receiver detect corruption or tampering before trusting the contents.

14.4.3 Alternative View: Postal Letter Analogy

Side-by-side analogy matching a mailed letter to a network packet, showing how the addressed envelope maps to the header, the letter body maps to the payload, and the seal or postmark check maps to the trailer integrity field.

The postal analogy is useful because the roles are the same: the outside carries routing information, the inside carries the message, and a final check confirms the message arrived in a valid state.


14.5 Knowledge Check: Packet Basics

A) Source, Destination, Data

B) Header, Payload, Trailer

C) Start, Middle, End

D) Address, Message, Signature

B) Header, Payload, Trailer

Every network packet, regardless of protocol, contains these three fundamental components:

  • Header: Contains routing and control information (source/destination addresses, length, protocol type)
  • Payload: The actual data being transmitted (sensor readings, commands, JSON data)
  • Trailer: Error detection (checksums or CRC values)

A) To compress the payload data

B) To store the device’s GPS coordinates

C) To verify packet authenticity and detect tampering

D) To encode the temperature reading

C) To verify packet authenticity and detect tampering

The MIC (Message Integrity Code) in LoRaWAN uses AES-128-CMAC to:

  • Verify that the packet came from a legitimate device
  • Detect any modification to the packet during transmission
  • This is similar to a digital signature or wax seal on a letter

A) 13%

B) 50%

C) 75%

D) 88%

D) 88%

Overhead Ratio = (Overhead bytes / Total packet size) x 100

  • Total packet: 2 bytes payload + 15 bytes overhead = 17 bytes
  • Overhead ratio: 15/17 = 88.2%

This high overhead is typical for LPWAN protocols that optimize for range and battery life rather than efficiency. For larger payloads, the overhead ratio decreases.


14.6 Header Fields Deep Dive

Understanding what each header field does helps you debug network issues and design efficient protocols.

14.6.1 Common Header Fields Explained

Packet header fields overview showing six common header fields arranged across a frame: source address, destination address, length, protocol type, sequence number, and flags, with each field connected to a short explanation and example values.

  • Source Address Purpose: identifies the sender. Example values: IP 192.168.1.100, MAC AA:BB:CC:DD:EE:FF
  • Destination Address Purpose: identifies the receiver. Example values: IP 10.0.0.1, DevAddr 0x0D1C2B3A
  • Length Purpose: size of payload in bytes. Example values: 64, 128, 1500 bytes
  • Protocol Type Purpose: how to interpret the data. Example values: 0x0800 (IPv4), 0x86DD (IPv6)
  • Sequence Number Purpose: order for reassembly. Example values: 0, 1, 2, 3...
  • Flags Purpose: control bits. Example values: SYN, ACK, FIN, ADR enabled

14.6.2 Why Sequence Numbers Matter

Sequence numbers serve multiple critical purposes:

  1. Packet Ordering: If packets arrive out of order, the receiver can reassemble them correctly
  2. Duplicate Detection: If the same sequence number arrives twice, the receiver knows it’s a duplicate
  3. Replay Attack Prevention: In LoRaWAN, if FCnt doesn’t increment, the network server rejects the packet
Security Insight: Replay Attacks

Without sequence numbers, an attacker could capture a valid “unlock door” packet and replay it later. The frame counter (FCnt) in LoRaWAN must always increment, making captured packets useless to attackers.

What header field prevents replay attacks in LoRaWAN?

A) DevAddr (Device Address)

B) FPort (Application Port)

C) FCnt (Frame Counter)

D) MHDR (MAC Header)

C) FCnt (Frame Counter)

The Frame Counter must always increment with each transmission. If an attacker captures a packet and replays it later, the network server will reject it because:

  • The FCnt in the replayed packet is now lower than expected
  • This makes captured packets useless to attackers
  • Both uplink and downlink have separate counters

14.7 Payload: Where Your Data Lives

The payload is the reason packets exist - it carries your actual information.

14.7.1 Payload Characteristics

  • Variable Size: can be 0 bytes up to the MTU limit.
  • Protocol-Independent: the header does not care what the payload contains.
  • Application-Defined: you choose the encoding, such as JSON, CBOR, or binary.
  • Encrypted Option: the payload can be encrypted end to end.

14.7.2 IoT Payload Examples

IoT payload examples comparing a compact temperature sensor reading, a GPS tracker status update, and a smart switch command, showing how packet payloads carry the application data while the header and trailer stay protocol-focused.

Design Tip: Keep Payloads Small

In bandwidth-constrained IoT systems, every byte matters:

  • Use binary encoding instead of JSON (save 80%+ space)
  • Pack multiple readings into one payload
  • Use compression for text data
  • Consider CBOR as a compact JSON alternative

Why do IoT protocols like LoRaWAN use small payloads?

A) To reduce manufacturing costs

B) To optimize for range, battery life, and regulatory compliance

C) To make packets easier to read

D) To improve CPU performance

B) To optimize for range, battery life, and regulatory compliance

LPWAN protocols like LoRaWAN use small payloads because:

  • Range: Longer transmission time at low data rates means more reliable delivery over long distances
  • Battery Life: Shorter transmissions consume less energy
  • Regulations: Many regions limit airtime (duty cycle) for unlicensed bands
  • Network Capacity: Smaller packets allow more devices to share the network

14.8 Trailer: Error Detection

The trailer ensures data integrity - that the packet wasn’t corrupted during transmission.

14.8.1 Error Detection Methods

  • Checksum Size: 1-2 bytes Detection capability: simple errors Common use: UDP, TCP
  • CRC-16 Size: 2 bytes Detection capability: burst errors up to 16 bits Common use: Modbus, USB
  • CRC-32 Size: 4 bytes Detection capability: burst errors up to 32 bits Common use: Ethernet, ZIP
  • MIC/MAC Size: 4+ bytes Detection capability: tampering plus transmission errors Common use: LoRaWAN, TLS

14.8.2 How CRC Works (Simplified)

Sender and receiver CRC workflow showing data bytes entering a CRC algorithm, the checksum being appended to the transmitted frame, and the receiver recalculating and comparing the value to accept or reject the packet.

At the receiver:

  1. Receiver performs the same CRC calculation on received data
  2. Compares calculated CRC with received CRC
  3. If they match: Data is valid
  4. If they differ: Data is corrupted, request retransmission

A packet’s CRC at the receiver doesn’t match the sender’s CRC. What happened?

A) The packet was encrypted

B) The packet was compressed

C) Data was corrupted during transmission

D) The payload was too large

C) Data was corrupted during transmission

CRC mismatch indicates that bits were flipped or lost during transmission due to:

  • Electromagnetic interference
  • Signal attenuation
  • Collision with another packet
  • Hardware malfunction

The receiver should discard the packet and request retransmission (if the protocol supports it).


Connect with Learning Hubs

This chapter connects to multiple learning resources across the IoT Class platform:

Interactive Learning:

  • Simulations Hub: Analyze real packets with Wireshark tutorials, packet dissection tools, and protocol analyzers
  • Knowledge Map: See how packet structure fits into the networking stack and protocol design
  • Quizzes Hub: Test your understanding of framing, error detection, and header parsing
  • Videos Hub: Watch step-by-step packet dissection demonstrations and protocol analysis

Hands-On Activities:

  • Network Traffic Analysis: Use Wireshark to capture and analyze packets from your own IoT devices
  • Protocol Simulators: Build your own packet structures and test framing techniques
  • Error Detection Calculator: Compute checksums and CRC values for practice packets
  • Header Comparison Tool: Compare overhead across different IoT protocols

Deep Dives:


Scenario: You’re debugging a smart factory where a PLC (Programmable Logic Controller) reads temperature from a Modbus TCP sensor. Wireshark captures this packet:

Raw packet (hex):

00 01 00 00 00 06 01 03 00 64 00 01

Question: Decode each field and extract the sensor address and function code.

14.8.3 Step 1: Understand Modbus TCP Packet Structure

  • Transaction ID Size: 2 bytes Purpose: matches requests and responses.
  • Protocol ID Size: 2 bytes Purpose: always 0x0000 for Modbus.
  • Length Size: 2 bytes Purpose: number of bytes following this field.
  • Unit ID Size: 1 byte Purpose: device address, also called slave ID.
  • Function Code Size: 1 byte Purpose: operation type.
  • Data Size: variable Purpose: function-specific payload.

14.8.4 Step 2: Parse the Packet Byte-by-Byte

00 01    00 00    00 06    01    03    00 64 00 01
^^^^^    ^^^^^    ^^^^^    ^^    ^^    ^^^^^^^^^^^
Trans    Proto    Length   Unit  Func  Data (4 bytes)
ID       ID                ID    Code

Field extraction:

  • Transaction ID Bytes: 0-1 Hex value: 00 01 Decoded value: 1 Interpretation: request/response pair #1.
  • Protocol ID Bytes: 2-3 Hex value: 00 00 Decoded value: 0 Interpretation: Modbus protocol.
  • Length Bytes: 4-5 Hex value: 00 06 Decoded value: 6 Interpretation: the next 6 bytes are Modbus data.
  • Unit ID Bytes: 6 Hex value: 01 Decoded value: 1 Interpretation: sensor at address 1.
  • Function Code Bytes: 7 Hex value: 03 Decoded value: 3 Interpretation: read holding registers.
  • Starting Address Bytes: 8-9 Hex value: 00 64 Decoded value: 100 Interpretation: register 100.
  • Quantity Bytes: 10-11 Hex value: 00 01 Decoded value: 1 Interpretation: read 1 register.

14.8.5 Step 3: Interpret the Request

What this packet means:

“Read 1 holding register starting at address 100 from device 1”

Function Code 03 (Read Holding Registers) is the most common Modbus function for reading sensor data.

14.8.6 Step 4: Expected Response

The sensor should respond with:

00 01 00 00 00 05 01 03 02 00 E1
^^^^^          ^^^^^ ^^ ^^ ^^^^^
Same Trans ID  Len=5 Unit Func Registers (2 bytes)

Response parsing:

  • Byte count Hex: 02 Value: 2 Meaning: 2 bytes of register data follow.
  • Register data Hex: 00 E1 Value: 225 Meaning: temperature = 22.5°C using value / 10.

14.8.7 Step 5: C Code to Parse Header

#include <stdint.h>
#include <arpa/inet.h>  // ntohs(): network-to-host byte order

struct modbus_tcp_header {
  uint16_t transaction_id;  // Bytes 0-1
  uint16_t protocol_id;     // Bytes 2-3 (always 0x0000)
  uint16_t length;          // Bytes 4-5
  uint8_t  unit_id;         // Byte 6
  uint8_t  function_code;   // Byte 7
};

void parse_modbus_packet(uint8_t *pkt, size_t len) {
  if (len < 8) return;
  struct modbus_tcp_header h;
  h.transaction_id = ntohs(*(uint16_t*)&pkt[0]);
  h.protocol_id    = ntohs(*(uint16_t*)&pkt[2]);
  h.length         = ntohs(*(uint16_t*)&pkt[4]);
  h.unit_id        = pkt[6];
  h.function_code  = pkt[7];

  printf("Txn: %u  Unit: %u  Func: 0x%02X  Len: %u\n",
         h.transaction_id, h.unit_id, h.function_code, h.length);

  // Parse register read request (function 0x03)
  if (h.function_code == 0x03 && len >= 12) {
    uint16_t addr = ntohs(*(uint16_t*)&pkt[8]);
    uint16_t qty  = ntohs(*(uint16_t*)&pkt[10]);
    printf("Read %u registers starting at 0x%04X\n", qty, addr);
  }
}

Output:

Transaction ID: 1
Protocol ID: 0 (should be 0)
Length: 6 bytes
Unit ID: 1
Function Code: 3 (Read Holding Registers)
Reading 1 registers starting at address 100

14.8.8 Key Takeaways

  1. Always check byte order - Modbus TCP uses big-endian (use ntohs() for uint16)
  2. Headers provide context - Transaction ID links requests to responses
  3. Function codes are standardized - Learn the common ones (0x03, 0x04, 0x06)
  4. Length field validates packet - Use it to detect truncated packets
  5. Parsing requires exact offsets - Off-by-one errors break everything

Real-world debugging: When Modbus sensors don’t respond, capture packets and check: - Transaction ID matches request/response? - Unit ID correct (common mistake: wrong device address)? - Function code valid for this device? - Register address within device’s range?


Common Pitfalls

Packet diagrams tempt people to focus on the useful data and ignore the bytes spent on addressing, counters, flags, and CRC fields. Always calculate total bytes on the wire, because radio energy, airtime, and duty-cycle limits depend on the entire frame, not just the payload.

Many packet bugs come from assuming a field is in the same place across protocols. Byte order, field width, optional headers, and bit-packed flags all vary. Use the protocol specification or a trusted capture decode instead of inferring structure from memory.

If you only decode the payload and ignore counters, length fields, and CRC or MIC values, you miss the reason the receiver rejected the packet. When troubleshooting captures, inspect the whole frame, especially the fields that prove ordering, authenticity, and integrity.

14.9 Summary

Packet anatomy is the foundation of all network communication:

  • Three Parts: Every packet contains Header (routing/control), Payload (data), and Trailer (error checking)
  • Header Fields: Source/destination addresses, length, type, sequence numbers, and flags
  • Payload: Variable-size section carrying actual sensor data or application messages
  • Trailer: Error detection using checksums or CRC values

Key Takeaways:

  • Headers provide metadata needed for routing and protocol operation
  • Payload size is limited by the Maximum Transmission Unit (MTU)
  • Understanding packet structure is essential for debugging with tools like Wireshark


14.10 Knowledge Check

14.11 What’s Next

Continue exploring packet structure with these related chapters:

  • Frame Delimiters and Boundaries Focus area: packet boundaries Key concepts: start/stop markers, preambles, length-delimited vs. character-stuffed framing
  • Error Detection Focus area: data integrity Key concepts: checksums, CRC polynomials, Hamming distance, error correction vs. detection
  • Protocol Overhead Focus area: efficiency analysis Key concepts: header comparison across protocols, encapsulation layers, overhead minimization
  • Data Formats for IoT Focus area: payload encoding Key concepts: JSON, CBOR, Protocol Buffers, MessagePack, and choosing compact representations
  • Sensor to Network Pipeline Focus area: end-to-end flow Key concepts: how raw sensor readings become network packets through the full processing chain
  • Data Representation Focus area: binary foundations Key concepts: hexadecimal notation, bitwise operations, and byte ordering for parsing packet fields

Continue to Frame Delimiters and Boundaries ->