7  Networking Hands-On Config

Key Concepts
  • Ping: A network diagnostic tool using ICMP echo request/reply to verify connectivity and measure round-trip time
  • Traceroute (tracert): A tool that reveals the path packets take through the network by exploiting TTL expiry at each hop
  • Netstat: A command that displays active network connections, listening ports, and routing table information
  • Wireshark: A packet capture tool that displays raw network frames with protocol decoding for each layer
  • Iperf: A network performance measurement tool that measures achievable TCP/UDP throughput between two hosts
  • Nmap: A network scanner that discovers active hosts and open ports in a subnet
  • tcpdump: A command-line packet capture tool; lightweight alternative to Wireshark, suitable for remote SSH sessions

7.1 In 60 Seconds

This hands-on chapter walks through configuring ESP32 devices on Wi-Fi networks, understanding port numbers used by IoT protocols (MQTT on 1883, CoAP on 5683, HTTP on 80/443), applying layer-by-layer troubleshooting methodology, and implementing basic network security practices for IoT deployments.

7.2 Learning Objectives

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

  • Configure IoT Networks: Set up ESP32 devices with proper Wi-Fi, IP, and DHCP network configuration
  • Identify and Classify Port Numbers: Differentiate common IoT protocol ports (MQTT 1883/8883, CoAP 5683/5684, HTTP 80/443) by range and security properties
  • Troubleshoot Networks: Apply systematic layer-by-layer troubleshooting to diagnose and resolve IoT connectivity failures
  • Implement Security Controls: Apply TLS encryption, credential management, and network segmentation practices to harden IoT deployments
  • Calculate Data Budgets: Evaluate bandwidth and latency trade-offs by computing protocol overhead ratios and monthly data consumption for IoT device fleets

This chapter gives you practical experience configuring network settings on real devices. Think of it as learning to drive by actually getting behind the wheel – you will set up IP addresses, test connections, and see firsthand how devices find and talk to each other on a network.

“Enough theory – let’s actually configure a real device!” said Max the Microcontroller, powering up an ESP32 board. “First, we tell it which Wi-Fi network to join and give it the password. Then it gets an IP address and we are connected!”

Sammy the Sensor watched excitedly. “Once we are on the network, we need to know which PORT to send data to. The MQTT broker listens on port 1883, like an apartment number in a building. If I send to the wrong port, my data goes nowhere!”

“When something goes wrong – and it WILL go wrong – troubleshoot from the bottom up,” advised Lila the LED. “First check Physical: is the device powered on and the antenna working? Then Data Link: can it see the Wi-Fi access point? Then Network: did it get an IP address? And finally Application: is the MQTT connection established?”

“That layered approach saves so much time,” agreed Bella the Battery. “Instead of randomly guessing, you systematically check each layer until you find the problem. And do not forget security – always change default passwords, use encrypted connections, and never send sensitive data over plain HTTP!”

7.3 Prerequisites

Before diving into this chapter, you should be familiar with:


7.4 Hands-On: Network Configuration

Time: ~15 min | Intermediate | P07.C14.U04

7.4.1 ESP32 Network Configuration Example

Instead of memorizing a sketch, focus on the evidence a correct sketch should print.

Stage What the ESP32 should do Evidence to record
Join Wi-Fi Connect to the intended SSID with the correct password WiFi.status() reports connected
Receive DHCP settings Get an IP address, subnet mask, gateway, and DNS server IP is not 0.0.0.0 or 169.254.x.x
Identify the device Report the device MAC address and optional hostname MAC address is unique on the LAN
Check signal quality Measure RSSI after association Better than about -70 dBm for stable Wi-Fi
Test reachability Try a simple outbound connection to a known host/port Gateway or internet test succeeds

Key Configuration Parameters:

Parameter Purpose Example
IP Address Device’s unique network identity 192.168.1.100
Subnet Mask Defines local network size 255.255.255.0 (/24 = 254 hosts)
Gateway Router to reach other networks 192.168.1.1
DNS Converts names to IP addresses 8.8.8.8 (Google DNS)
MAC Address Hardware identifier DC:A6:32:AB:CD:EF

Objective: Read the network configuration an ESP32 receives from DHCP and understand which fields prove that the device is ready to communicate.

Setup: Use the diagnostic activities in this chapter to understand the fields. If you later run an ESP32 sketch, make it print the evidence below rather than treating the code as the learning goal.

Explorer Output Checklist:

Field Healthy output What it proves
Wi-Fi status Connected SSID/password and association worked
IP address Private address such as 192.168.1.45 DHCP or static IP assignment worked
Subnet mask Usually /24 in small LANs Device knows which IPs are local
Gateway Router address such as 192.168.1.1 Device has a path off the subnet
DNS server Router or resolver address Hostnames can be resolved
RSSI Better than about -70 dBm Signal is likely stable enough
Outbound test Known host/port succeeds Routing, NAT, and firewall permit traffic

What to Observe:

  1. Watch the Serial Monitor for DHCP-assigned IP, subnet mask, and gateway
  2. The MAC address is a unique hardware identifier – every ESP32 has a different one
  3. RSSI updates show signal strength over time (-30 dBm = excellent, -70 dBm = acceptable)
  4. Try changing WiFi.getHostname() before WiFi.begin() with WiFi.setHostname("my-sensor") to customize the device name on the network

7.4.2 Python Network Scanner

A scanner should be used only on networks where you have permission. The learning objective is to understand the investigation logic:

Step Question Evidence
Define scope Which subnet is approved for testing? Example: 192.168.1.0/24 with owner approval
Choose ports Which IoT services are you checking? MQTT 1883/8883, CoAP 5683/5684, HTTP 80/443, SSH 22
Test one host first Does a known device respond as expected? Confirms the tool and firewall behavior
Scan carefully Are results limited to approved hosts and ports? Avoids noisy or unauthorized probing
Interpret results Are any insecure services exposed? Plain MQTT, HTTP, Telnet, or unexpected open ports need review
Try It: Subnet & IP Address Explorer

Enter a base IP address and subnet mask to see how many hosts fit in the network, the valid IP range, and the broadcast address.


7.5 Port Numbers

Time: ~8 min | Foundational | P07.C14.U05

Port numbers identify specific applications or services on a device. They range from 0 to 65535.

7.5.1 Common IoT Protocol Ports

Port Protocol Description Security
80 HTTP Web servers, REST APIs Unencrypted
443 HTTPS Secure web, TLS Encrypted
1883 MQTT IoT messaging Unencrypted
8883 MQTTS MQTT over TLS Encrypted
5683 CoAP Constrained devices Unencrypted
5684 CoAPS CoAP over DTLS Encrypted
22 SSH Secure shell access Encrypted
23 Telnet Remote access Unencrypted (avoid!)
502 Modbus TCP Industrial protocols Unencrypted
5353 mDNS Local device discovery N/A
123 NTP Time synchronization N/A
53 DNS Domain name resolution Usually unencrypted
Security Best Practice

Always use encrypted ports in production:

  • Use 8883 instead of 1883 for MQTT
  • Use 5684 instead of 5683 for CoAP
  • Use 443 instead of 80 for HTTP
  • Never use Telnet (port 23) - use SSH (port 22) instead

Unencrypted ports are acceptable only for development and testing on isolated networks.

7.5.2 Port Number Ranges

Range Type Examples
0-1023 Well-known ports HTTP (80), HTTPS (443), SSH (22)
1024-49151 Registered ports MQTT (1883), CoAP (5683)
49152-65535 Dynamic/private Client-side connections
Try It: IoT Port Number Explorer

Select an IoT protocol to see its port number, security status, and where it falls in the port range. You can also enter any port number to classify it.


7.6 Network Troubleshooting

Time: ~12 min | Intermediate | P07.C14.U06

7.6.1 Layer-by-Layer Troubleshooting Approach

When an IoT device won’t connect, work systematically from Physical layer up:

Flowchart showing layer-by-layer IoT troubleshooting: start at Physical (power, signal), then Data Link (SSID, auth), Network (IP/DHCP), and Application (port, firewall), with pass/fail branches at each layer leading to a root-cause fix
Figure 7.1: Layer-by-layer troubleshooting flowchart for IoT connectivity issues

7.6.2 Troubleshooting Checklist by Layer

Layer 1 (Physical):

  • Is the device powered on?
  • Is RSSI > -70 dBm? (e.g., -55 dBm is good; -85 dBm is too weak)
  • Is the antenna connected properly?
  • Any physical obstacles (metal, concrete)?
  • Is the device within range?

Layer 2 (Data Link):

  • Correct SSID? (case-sensitive)
  • Correct password? (case-sensitive)
  • MAC address whitelisted? (if MAC filtering enabled)
  • Correct Wi-Fi channel? (2.4 GHz vs 5 GHz - ESP32 only supports 2.4 GHz)
  • Channel congestion?

Layer 3 (Network):

  • Did device get IP address? (check DHCP lease)
  • IP address conflict? (two devices with same IP)
  • Correct subnet mask?
  • Correct gateway configured?

Layer 4 (Transport) / Layer 7 (Application):

  • Can ping the gateway? (ping 192.168.1.1)
  • Can ping external IP? (ping 8.8.8.8)
  • DNS resolution working? (nslookup google.com)
  • Firewall blocking ports?
  • Correct protocol port configured?

7.6.3 ESP32 Diagnostic Commands

When debugging an ESP32, collect these observations in order:

Check Healthy result If it fails
Wi-Fi status Connected Recheck SSID, password, channel, and MAC filtering
RSSI Better than about -70 dBm Move closer, change antenna, or reduce obstruction
IP address Valid LAN address Check DHCP server or static IP settings
Gateway Router address in same subnet Fix DHCP option or static gateway
DNS Resolver address present Set a working DNS server
External service Known host/port reachable Check firewall, NAT, and upstream internet

7.6.4 Common Issues and Solutions

Problem Symptoms Solution
Weak signal RSSI < -70 dBm, frequent disconnects Move closer, add antenna, use extender
Wrong credentials Connection timeout, auth failure Verify SSID/password case
No IP address IP shows 0.0.0.0 or 169.254.x.x Check DHCP server, try static IP
Can’t reach gateway Ping gateway fails Check subnet mask, gateway IP
Can’t reach internet Ping 8.8.8.8 fails Check ISP, router, NAT
DNS not working Names fail, IPs work Check DNS server configuration
Port blocked Connection refused Check firewall rules
Try It: Layer-by-Layer Troubleshooting Simulator

Select a failure scenario and step through the OSI layers to diagnose the problem, just as you would with a real IoT device. Each layer check reveals whether the issue is at that layer or if you should continue up the stack.


7.7 Security Basics

Time: ~10 min | Foundational | P07.C14.U07

IoT Security Fundamentals

IoT devices are prime targets for attacks due to:

  • Often deployed in physical locations with no supervision
  • Many use default credentials
  • Limited resources for security features
  • Long deployment lifetimes with infrequent updates

7.7.1 Essential Security Practices

1. Change Default Credentials

Weak pattern Safer pattern
Shared default username such as admin Unique device identity such as sensor_temp_001
Shared default password such as admin Random per-device secret stored outside source code
One credential reused across a fleet Rotate or revoke one device without breaking the fleet
Credentials committed to a repository Provision through a secure setup process

2. Use TLS Encryption

Insecure choice Production choice Why it matters
MQTT on port 1883 MQTTS on port 8883 Encrypts credentials and sensor payloads
CoAP on port 5683 CoAPS on port 5684 Adds DTLS protection for constrained devices
HTTP on port 80 HTTPS on port 443 Prevents plain-text API traffic
No certificate validation Validate broker/server certificate Prevents impersonation and man-in-the-middle attacks

3. Network Segmentation

Diagram showing network segmentation with IoT devices on a dedicated VLAN, separated from corporate LAN and internet by a firewall, preventing lateral movement of attacks between zones
Figure 7.2: Network segmentation isolates IoT devices from corporate networks

4. Firmware Updates

  • Implement secure OTA (Over-The-Air) updates
  • Sign firmware images cryptographically
  • Validate signatures before applying updates
  • Have rollback mechanism for failed updates

5. Minimal Attack Surface

  • Disable unused services and ports
  • Remove debugging interfaces in production
  • Use principle of least privilege
  • Log security events for monitoring

7.7.2 Security Checklist

Try It: IoT Security Score Calculator

Rate your IoT deployment against the seven security checklist items to get an instant security score and prioritized recommendations.


7.8 Bandwidth and Latency Considerations

Time: ~8 min | Foundational | P07.C14.U08

7.8.1 IoT vs Traditional IT: Key Differences

Aspect Traditional IT IoT
Data Size MB to GB Bytes to KB
Traffic Pattern Continuous Bursty, periodic
Latency Tolerance Seconds OK ms to seconds
Bandwidth Priority High throughput Low power
Reliability High availability Graceful degradation

7.8.2 Typical IoT Data Sizes

Data Type Size Frequency Daily Data
Temperature reading 4 bytes Every 5 min 1.2 KB
GPS coordinates 16 bytes Every 30 sec 46 KB
Accelerometer sample 12 bytes 100 Hz 4.3 MB
Image capture 50 KB Every hour 1.2 MB
Audio clip (10s) 160 KB On event Variable

Calculate the data budget for a wearable health monitor transmitting heart rate (2 bytes), step count (2 bytes), and GPS position (16 bytes) every 15 seconds over a cellular LTE-M connection:

Total payload per sample:

\(\text{Payload} = 2 + 2 + 16 = 20 \text{ bytes}\)

Add CoAP/UDP/IP headers (4 + 8 + 20 = 32 bytes overhead):

\(\text{Total packet} = 20 + 32 = 52 \text{ bytes}\)

Daily transmission count:

\(\text{Transmissions per day} = \frac{86400 \text{ s}}{15 \text{ s}} = 5,760\)

Daily data volume:

\(\text{Daily data} = 5,760 \times 52 = 299,520 \text{ bytes} \approx 293 \text{ KB/day}\)

Monthly data (30 days):

\(\text{Monthly data} = 293 \times 30 = 8,790 \text{ KB} \approx 8.6 \text{ MB/month}\)

For a 10 MB/month cellular plan at $5/month, this device consumes 86% of the data cap just for sensor telemetry, leaving 1.4 MB for firmware updates or emergency alerts. Reducing reporting frequency to 30 seconds would halve the data usage to 4.3 MB/month (43% utilization).

7.8.3 Protocol Overhead Comparison

Protocol Header Size Typical Payload Overhead Ratio
HTTP ~300 bytes 10 bytes 30:1
MQTT 2-5 bytes 10 bytes 0.5:1
CoAP 4 bytes 10 bytes 0.4:1
UDP raw 8 bytes 10 bytes 0.8:1

For a 10-byte temperature reading sent via HTTP vs CoAP, calculate the total bandwidth consumed and transmission time over a 9600 bps serial link:

HTTP over TCP/IP:

\(\text{HTTP packet} = 10 \text{ (data)} + 300 \text{ (HTTP headers)} + 20 \text{ (TCP)} + 20 \text{ (IP)} = 350 \text{ bytes}\)

Transmission time:

\(\text{Time}_\text{HTTP} = \frac{350 \text{ bytes} \times 8 \text{ bits/byte}}{9600 \text{ bps}} = 0.292 \text{ seconds}\)

CoAP over UDP/IP:

\(\text{CoAP packet} = 10 \text{ (data)} + 4 \text{ (CoAP)} + 8 \text{ (UDP)} + 20 \text{ (IP)} = 42 \text{ bytes}\)

Transmission time:

\(\text{Time}_\text{CoAP} = \frac{42 \times 8}{9600} = 0.035 \text{ seconds}\)

Efficiency comparison:

\(\text{Speedup} = \frac{0.292}{0.035} = 8.3\times \text{ faster}\)

For battery-powered sensors transmitting every 60 seconds, HTTP keeps the radio active for ~0.3s per transmission (0.5% duty cycle), while CoAP uses only 0.035s (0.06% duty cycle) – an 8× reduction in radio-on time and proportional battery savings.

Optimization Strategies

Reduce Overhead:

  • Use MQTT or CoAP instead of HTTP for small payloads
  • Use binary formats (CBOR, MessagePack) instead of JSON
  • Aggregate multiple readings into single transmission

Manage Bandwidth:

  • Adjust reporting frequency based on data change rate
  • Use compression for larger payloads
  • Implement local filtering/aggregation

Optimize Latency:

  • Use UDP for non-critical real-time data
  • Keep persistent connections when possible
  • Colocate edge processing near devices
Try It: IoT Data Budget Calculator

Configure your IoT device parameters to calculate daily and monthly data usage, compare protocol overhead, and see whether your deployment fits within a cellular data plan.


7.9 Best Practices Summary

Time: ~5 min | Intermediate | P07.C14.U09

7.9.1 Network Design

  1. Choose the right protocol for your constraints (power, range, bandwidth)
  2. Design for failure - networks are unreliable, buffer data locally
  3. Plan IP addressing - use static IPs for critical devices, document allocations
  4. Segment networks - isolate IoT from corporate networks

7.9.2 Implementation

  1. Test in realistic conditions - not just on your desk
  2. Monitor signal strength - RSSI should be > -70 dBm for reliability
  3. Implement reconnection logic - networks will drop, handle gracefully
  4. Log network events - aids troubleshooting and security monitoring

7.9.3 Security

  1. Encrypt everything - TLS/DTLS is mandatory in production
  2. Authenticate everything - no anonymous connections
  3. Update regularly - vulnerabilities are discovered continuously
  4. Assume breach - design for detection and containment

7.10 Review: Match Protocols to Ports

7.11 Review: Order Troubleshooting Steps


7.12 Knowledge Check

Scenario: An ESP32 temperature sensor successfully connects to Wi-Fi but cannot send MQTT messages to broker at mqtt.example.com:8883.

Given:

  • Device: ESP32 with correct SSID/password
  • Wi-Fi: Connected, RSSI = -52 dBm (excellent)
  • IP address: 10.0.1.45 (obtained via DHCP)
  • Gateway: 10.0.1.1
  • MQTT broker: mqtt.example.com port 8883 (TLS)

Systematic Troubleshooting (Layer-by-Layer):

Layer 1 (Physical): ✓ PASS - Signal strength excellent (-52 dBm) - Device powered and antenna functional

Layer 2 (Data Link): ✓ PASS - Wi-Fi connected - Obtained IP via DHCP

Layer 3 (Network): Test connectivity

Test Result Meaning
Reach gateway 10.0.1.1 Pass Local subnet and default gateway are reachable
Reach external IP 8.8.8.8 Pass Routing and NAT are working

✓ PASS - Network layer working

Layer 4-7 (Transport/Application): Test service

Test Result Meaning
Resolve mqtt.example.com Pass, returns broker IP DNS is working
Connect to broker port 8883 Fail Firewall or broker policy blocks secure MQTT

Root Cause Identified: Firewall blocks port 8883

Solution Options:

  1. Open firewall port 8883 (requires network admin)
  2. Use MQTT-over-WebSocket on port 443 (works immediately):
Workaround When to use it Trade-off
Open port 8883 You control the network firewall Cleanest standard MQTTS path
MQTT over WebSocket on 443 Corporate firewall only allows HTTPS-like outbound traffic Requires broker and client WebSocket support
HTTP REST fallback MQTT cannot be permitted Simpler firewall path, but usually more overhead
  1. Use HTTP REST API (fallback if MQTT unavailable)

Key Insight: Layer-by-layer testing isolated the exact failure point (port 8883 blocked), avoiding guesswork. WebSocket tunneling over port 443 bypasses most firewalls.


Common Pitfalls

Ping RTT measures round-trip time (sender to receiver and back). One-way latency is approximately RTT/2 for symmetric paths. Fix: never quote RTT as “the latency” in system design documents; always specify one-way or round-trip explicitly.

Capturing on a busy network produces millions of packets per minute, making analysis impossible. Fix: always apply a capture filter (e.g., host 192.168.1.100 and port 1883) before starting a capture.

Running Iperf in TCP mode on the client and UDP mode on the server gives nonsensical results. Fix: explicitly specify the same protocol (-u for UDP) on both client and server, and verify the server is in listening mode before starting the client.

7.13 What’s Next

Now that you can configure, troubleshoot, and secure IoT networks, continue with the chapters below:

Topic Chapter Description
Labs and Practice Networking Basics: Labs Interactive labs, Python implementations, and comprehensive knowledge checks with detailed answers
Network Topologies Topologies Introduction Star, mesh, tree, and hybrid topologies — trade-offs for IoT scale and reliability
Transport Protocols Transport Fundamentals TCP vs UDP, reliability guarantees, and which to choose for sensor data
Application Protocols MQTT Deep Dive Publish-subscribe messaging, QoS levels, and broker configuration for IoT
Security Fundamentals Threat Modeling Fundamentals Common attack vectors on IoT networks and systematic threat modelling
Edge Computing Edge and Fog Computing Moving computation closer to devices to reduce bandwidth and latency

7.14 Label the Diagram

7.15 Code Challenge