Capture and filter network traffic using Wireshark, tcpdump, and tshark for IoT protocol debugging
In 60 Seconds
IoT network traffic analysis uses protocol analyzers (Wireshark, tcpdump, specialized RF sniffers) to capture and decode actual device communications, revealing protocol timing issues, unexpected retransmissions, and security anomalies that are invisible to simulation but critical to production reliability.
Analyse MQTT, CoAP, Zigbee, and LoRaWAN traffic patterns to validate protocol implementations
Diagnose connectivity issues, packet loss, and latency bottlenecks through traffic inspection
Apply traffic analysis techniques to detect security threats and anomalous device behaviour
For Beginners: Network Traffic Analysis
Network traffic analysis is like being a detective investigating how your IoT devices communicate. Just as you might watch security camera footage to understand what happened in a building, traffic analysis tools like Wireshark let you “watch” the data packets flowing through your network. You can see exactly what your temperature sensor sent to the cloud, whether the message arrived successfully, and if there were any problems along the way. This is essential for diagnosing connectivity issues, validating your protocols work correctly, and detecting security threats.
Sensor Squad: Spying on Network Messages!
“Traffic analysis is like being a postal inspector who opens letters to check what is inside,” said Max the Microcontroller. “Except we are opening network packets! Tools like Wireshark let you see every message flowing through your IoT network – what Sammy is sending, where it is going, and how long it takes to arrive.”
Sammy the Sensor demonstrated: “Say I send a temperature reading using MQTT. Traffic analysis shows me the exact packet: timestamp, source address, destination address, protocol, and the data itself. If the reading never arrives at the cloud, I can trace exactly where it got lost – like following footprints in the snow!”
“Traffic analysis is also a security tool,” added Lila the LED. “If a hacker has compromised one of our devices, you might see strange traffic patterns – like a sensor suddenly sending data to an unknown server at 3 AM. That is a red flag!” Bella the Battery noted, “Understanding your traffic also helps me last longer – if you discover your device is sending unnecessary data, you can optimize and save energy!”
Interactive: Interactive Packet Analyzer
17.2 Overview
Network traffic analysis is the process of capturing, examining, and interpreting data packets flowing through a network. For IoT systems, traffic analysis serves multiple critical purposes: validating protocol implementations, diagnosing connectivity issues, measuring performance, detecting security threats, and understanding device behavior.
This comprehensive topic is covered across four focused chapters:
colors = {return {navy:"#2C3E50",teal:"#16A085",orange:"#E67E22",blue:"#3498DB",gray:"#7F8C8D",purple:"#9B59B6",red:"#E74C3C" }}// Tool datatoolsData = [ {name:"Wireshark",useCase:"Interactive deep protocol analysis",complexity:3,cost:0,remoteFriendly:1,automation:1,color: colors.navy }, {name:"tcpdump",useCase:"Remote/headless capture",complexity:2,cost:0,remoteFriendly:5,automation:3,color: colors.teal }, {name:"tshark",useCase:"Scriptable analysis & CI/CD",complexity:4,cost:0,remoteFriendly:4,automation:5,color: colors.blue }, {name:"Zigbee Sniffer",useCase:"802.15.4 wireless capture",complexity:3,cost:4,remoteFriendly:2,automation:2,color: colors.orange }, {name:"BLE Sniffer",useCase:"Bluetooth Low Energy",complexity:3,cost:3,remoteFriendly:2,automation:2,color: colors.purple }, {name:"Logic Analyzer",useCase:"UART/SPI/I2C debugging",complexity:4,cost:3,remoteFriendly:1,automation:3,color: colors.red }]viewof selectedMetric = Inputs.select( ["complexity","cost","remoteFriendly","automation"], {label:"Compare tools by:",format: x => ({complexity:"Learning Complexity (1=Easy, 5=Hard)",cost:"Cost (0=Free, 5=Expensive)",remoteFriendly:"Remote Access Friendliness",automation:"Automation Capability" })[x] }){const width =700;const height =400;const margin = {top:40,right:30,bottom:100,left:60};const svg = d3.create("svg").attr("width", width).attr("height", height).attr("viewBox", [0,0, width, height]).style("max-width","100%").style("height","auto");const x = d3.scaleBand().domain(toolsData.map(d => d.name)).range([margin.left, width - margin.right]).padding(0.2);const y = d3.scaleLinear().domain([0,5]).range([height - margin.bottom, margin.top]);// Bars svg.selectAll("rect").data(toolsData).join("rect").attr("x", d =>x(d.name)).attr("y", d =>y(d[selectedMetric])).attr("width", x.bandwidth()).attr("height", d =>y(0) -y(d[selectedMetric])).attr("fill", d => d.color).attr("rx",4);// Value labels on bars svg.selectAll(".value-label").data(toolsData).join("text").attr("class","value-label").attr("x", d =>x(d.name) + x.bandwidth() /2).attr("y", d =>y(d[selectedMetric]) -5).attr("text-anchor","middle").style("fill", colors.navy).style("font-size","14px").style("font-weight","600").text(d => d[selectedMetric]);// X axis svg.append("g").attr("transform",`translate(0,${height - margin.bottom})`).call(d3.axisBottom(x)).selectAll("text").style("text-anchor","end").attr("dx","-.8em").attr("dy",".15em").attr("transform","rotate(-45)").style("font-size","12px").style("fill", colors.navy);// Y axis svg.append("g").attr("transform",`translate(${margin.left},0)`).call(d3.axisLeft(y).ticks(5)).style("font-size","12px").style("color", colors.navy);// Y axis labelconst metricLabels = {complexity:"Complexity Level",cost:"Cost Level",remoteFriendly:"Remote Friendliness",automation:"Automation Score" }; svg.append("text").attr("transform","rotate(-90)").attr("x",-(height /2)).attr("y",15).attr("text-anchor","middle").style("font-size","14px").style("fill", colors.navy).style("font-weight","600").text(metricLabels[selectedMetric]);// Title svg.append("text").attr("x", width /2).attr("y",20).attr("text-anchor","middle").style("font-size","16px").style("fill", colors.navy).style("font-weight","700").text("Traffic Analysis Tool Comparison");return svg.node();}
Interpretation: Lower complexity is easier to learn. Higher remote-friendliness means better for SSH/headless access. Higher automation means better for CI/CD pipelines.
Essential Wireshark Filters:
mqtt # All MQTT traffic
coap # All CoAP traffic
ip.addr == 192.168.1.100 # Specific device
tcp.analysis.retransmission # Retransmissions only
frame.time_delta > 1 # Packets with >1s gap
Essential tcpdump Commands:
# Capture MQTT traffic to filesudo tcpdump -i eth0 port 1883 -w mqtt_capture.pcap# Remote capture with live Wiresharkssh user@gateway "tcpdump -w -"|wireshark-k-i-
Worked Example: Diagnosing MQTT Connection Failures
Scenario: An IoT temperature sensor publishes to AWS IoT Core every 60 seconds. After 2-3 hours, the connection drops and never reconnects. System logs show “MQTT connection lost” but no root cause.
Step 1: Capture Traffic
# Capture MQTT traffic on port 8883 (MQTT over TLS)sudo tcpdump -i wlan0 port 8883 -w mqtt_failure.pcap -v
At timestamp 2:45:35 (30 seconds after last publish):
BROKER → CLIENT: TCP FIN (connection close initiated by broker)
CLIENT → BROKER: TCP ACK
No PINGREQ from client!
Expected behavior: - KeepAlive = 60s - Client should send PINGREQ every 45-60 seconds (1.5× keepalive / 1.0× keepalive) - Last PUBLISH at 2:45:05, next PINGREQ expected by 2:46:05
Putting Numbers to It
Calculate MQTT keepalive timing for this connection failure scenario:
Lesson: Traffic analysis revealed the client violated MQTT keepalive protocol. Without Wireshark, this would have been impossible to diagnose from logs alone.
Decision Framework: Choosing the Right Traffic Analysis Tool
When diagnosing IoT network issues, select the appropriate tool based on your access level and requirements:
• Hardware probe needed • Limited to wired protocols
Sensor communication debugging
Decision Tree:
Q1: Can you access the network traffic path?
├─ YES: Is it wired (Ethernet/Wi-Fi)?
│ ├─ YES: Can you use GUI?
│ │ ├─ YES: Use **Wireshark** (best for learning/exploring)
│ │ └─ NO: Use **tcpdump** → save .pcap → analyze later on desktop
│ └─ NO: Is it Zigbee/Thread?
│ ├─ YES: Use **Zigbee Sniffer** (TI CC2531, Nordic nRF Sniffer)
│ └─ NO: Use **BLE Sniffer** (Nordic, Adafruit)
└─ NO: Is it sensor-to-MCU communication (I2C/SPI/UART)?
└─ YES: Use **Logic Analyzer** (Saleae, DSLogic)
Q2: Do you need automation/scripting?
├─ YES: Use **tshark** with filters
└─ NO: Use **Wireshark** GUI
Real-World Example:
Scenario: Smart home with 50 Zigbee devices, intermittent light switch failures.
Step 1: Use Zigbee sniffer to capture over-the-air traffic - Tool: TI CC2531 USB dongle ($25) + Wireshark Zigbee plugin - Capture all 802.15.4 frames on channel 15
Decision: Signal strength issue, not protocol problem. Move coordinator or add Zigbee router.
Key Takeaway: Right tool (Zigbee sniffer) revealed RF issue that application-level logs couldn’t show.
Common Mistake: Ignoring TLS Encryption
The Mistake: An engineer tries to analyze MQTT traffic with Wireshark but sees only encrypted gibberish because the IoT device uses MQTT over TLS (port 8883), not plain MQTT (port 1883).
Why It Happens:
Modern IoT protocols use TLS encryption for security: - MQTT over TLS: Port 8883 (encrypted) - CoAP over DTLS: Port 5684 (encrypted) - HTTPS: Port 443 (encrypted)
Wireshark shows:
TLSv1.2 Application Data (encrypted)
TLSv1.2 Application Data (encrypted)
...
No MQTT dissection, no readable payloads!
The Problem:
Without decryption, you can only see: - Connection establishment (TCP handshake) - TLS handshake (negotiation) - Encrypted application data (opaque)
MQTT: Sending CONNECT
MQTT: Received CONNACK
MQTT: Publishing to topic iot/sensors/temp: {"temperature":22.5}
Not as detailed as Wireshark, but often sufficient.
Best Practice:
Development: Use unencrypted connections for easy debugging
Staging: Use TLS with key logging
Production: Accept that traffic is opaque (monitor via application logs)
Remember: If you can’t decrypt TLS traffic, you can still analyze: - Connection timing and frequency - Packet sizes (revealing message patterns) - TCP-level errors (retransmissions, resets) - TLS handshake failures
1. Capturing Traffic Without a Promiscuous Mode Adapter
A standard Wi-Fi adapter only captures packets addressed to its own MAC address. Analyzing broadcast collisions or neighbor communications requires a Wi-Fi adapter in monitor/promiscuous mode, which many built-in laptop adapters do not support. Use a dedicated USB Wi-Fi adapter known to support monitor mode.
2. Analyzing Only Successful Packets and Ignoring Retransmissions
Protocol analyzers show both original transmissions and retransmissions. Counting all packets without filtering retransmissions gives inflated traffic estimates. Conversely, ignoring the retransmission rate misses a key reliability indicator — high retransmission rates signal a degraded link.
3. Not Filtering Capture to the Relevant Protocol
Capturing all traffic on a busy network fills disk rapidly and makes analysis difficult. Use capture filters (not display filters) to limit captured packets to the specific device MAC address, IP range, or protocol port being analyzed. This reduces storage requirements by 10–100× on congested networks.
4. Drawing Conclusions From Traffic During Normal Operation Only
Analyze traffic under stress conditions too: during network congestion, node join/rejoin events, OTA firmware updates, and after gateway reboots. Bugs and performance degradations almost always appear under stress, not during steady-state normal operation.
Label the Diagram
17.10 What’s Next
Begin with Traffic Analysis Fundamentals to learn about capture points, promiscuous mode, and filter strategies essential for effective network analysis.