7 Networking Hands-On Config
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
For Beginners: Networking Hands-On Practice
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.
Sensor Squad: Getting Our Hands Dirty!
“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:
- Networking Basics: Introduction: Core networking concepts including layers, IP addressing, and network types
- Networking Basics: Protocols and MAC: Understanding protocol layers and MAC classification
7.4 Hands-On: Network Configuration
7.4.1 ESP32 Network Configuration Example
#include <WiFi.h>
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin("MyNetwork", "MyPassword");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Display network information
Serial.println("\n=== Network Configuration ===");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
Serial.print("Subnet Mask: ");
Serial.println(WiFi.subnetMask());
Serial.print("Gateway: ");
Serial.println(WiFi.gatewayIP());
Serial.print("DNS: ");
Serial.println(WiFi.dnsIP());
Serial.print("MAC Address: ");
Serial.println(WiFi.macAddress());
Serial.print("Signal Strength (RSSI): ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
}
void loop() {
// Your IoT application code here
}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 |
7.4.2 Python Network Scanner
#!/usr/bin/env python3
"""Simple network scanner for IoT devices."""
import socket
import concurrent.futures
from typing import List, Tuple
def scan_host(ip: str, port: int) -> Tuple[str, int, bool]:
"""Check if a host has a port open."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, port))
sock.close()
return (ip, port, result == 0)
except socket.error:
return (ip, port, False)
def scan_network(base_ip: str, ports: List[int]) -> List[dict]:
"""Scan network for devices with open ports."""
devices = []
tasks = []
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Generate all IP/port combinations
for i in range(1, 255):
ip = f"{base_ip}.{i}"
for port in ports:
tasks.append(executor.submit(scan_host, ip, port))
# Collect results
for future in concurrent.futures.as_completed(tasks):
ip, port, is_open = future.result()
if is_open:
devices.append({"ip": ip, "port": port})
return devices
if __name__ == "__main__":
# Common IoT ports
iot_ports = [80, 443, 1883, 8883, 5683, 22]
print("Scanning local network for IoT devices...")
found = scan_network("192.168.1", iot_ports)
for device in found:
print(f"Found: {device['ip']}:{device['port']}")7.5 Port Numbers
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 |
7.6 Network Troubleshooting
7.6.1 Layer-by-Layer Troubleshooting Approach
When an IoT device won’t connect, work systematically from Physical layer up:
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
// Check Wi-Fi status
Serial.println(WiFi.status()); // WL_CONNECTED = 3
// Check signal strength
int rssi = WiFi.RSSI();
Serial.print("Signal: ");
Serial.print(rssi);
Serial.println(" dBm");
// Check IP configuration
Serial.print("IP: ");
Serial.println(WiFi.localIP());
Serial.print("Gateway: ");
Serial.println(WiFi.gatewayIP());
// Check connectivity (simple ping equivalent)
WiFiClient client;
if (client.connect("8.8.8.8", 53)) {
Serial.println("Internet: OK");
client.stop();
} else {
Serial.println("Internet: FAIL");
}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 |
7.7 Security Basics
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
// BAD: Default credentials
const char* mqtt_user = "admin";
const char* mqtt_pass = "admin";
// GOOD: Unique credentials per device
const char* mqtt_user = "sensor_temp_001";
const char* mqtt_pass = "Xk9#mP2@vL5!nQ8$";2. Use TLS Encryption
// BAD: Unencrypted MQTT
client.connect("broker.example.com", 1883);
// GOOD: TLS-encrypted MQTT
WiFiClientSecure secureClient;
secureClient.setCACert(root_ca);
client.setClient(secureClient);
client.connect("broker.example.com", 8883);3. Network Segmentation
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
7.8 Bandwidth and Latency Considerations
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 |
Putting Numbers to It
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 |
Putting Numbers to It
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
7.9 Best Practices Summary
7.9.1 Network Design
- Choose the right protocol for your constraints (power, range, bandwidth)
- Design for failure - networks are unreliable, buffer data locally
- Plan IP addressing - use static IPs for critical devices, document allocations
- Segment networks - isolate IoT from corporate networks
7.9.2 Implementation
- Test in realistic conditions - not just on your desk
- Monitor signal strength - RSSI should be > -70 dBm for reliability
- Implement reconnection logic - networks will drop, handle gracefully
- Log network events - aids troubleshooting and security monitoring
7.9.3 Security
- Encrypt everything - TLS/DTLS is mandatory in production
- Authenticate everything - no anonymous connections
- Update regularly - vulnerabilities are discovered continuously
- Assume breach - design for detection and containment
7.10 Knowledge Check
Worked Example: Troubleshooting IoT Device Connection Failure
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.comport 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 1: Can ping gateway?
WiFiClient client;
if (client.connect("10.0.1.1", 80)) {
Serial.println("Gateway: OK");
} // Result: OK
// Test 2: Can ping external IP?
if (client.connect("8.8.8.8", 53)) {
Serial.println("Internet: OK");
} // Result: OK✓ PASS - Network layer working
Layer 4-7 (Transport/Application): Test service
// Test 3: Can resolve DNS?
IPAddress brokerIP;
WiFi.hostByName("mqtt.example.com", brokerIP);
Serial.println(brokerIP); // Result: 54.231.10.5
// ✓ PASS - DNS working
// Test 4: Can connect to broker port?
WiFiClientSecure secureClient;
if (secureClient.connect("mqtt.example.com", 8883)) {
Serial.println("MQTT port: OK");
} else {
Serial.println("MQTT port: FAIL");
}
// × FAIL - Port 8883 blockedRoot Cause Identified: Firewall blocks port 8883
Solution Options:
- Open firewall port 8883 (requires network admin)
- Use MQTT-over-WebSocket on port 443 (works immediately):
// Change connection from:
client.connect("mqtt.example.com", 8883);
// To:
client.connect("mqtt.example.com", 443, "/mqtt");- 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
1. Interpreting Ping Round-Trip Time as One-Way Latency
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.
2. Not Filtering Wireshark Captures on Busy Networks
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.
3. Running Iperf Without Matching Protocol Settings on Both Sides
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.11 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 | Network Topologies Overview | Star, mesh, tree, and hybrid topologies — trade-offs for IoT scale and reliability |
| Transport Protocols | Transport Protocols Overview | 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 | IoT Security Threats | 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 |