Integrated Lab Assessment: An exercise combining hands-on lab work with a written quiz to verify both practical skills and theoretical understanding
Lab-Quiz Connection: The practice of deriving quiz questions directly from lab observations, ensuring the quiz tests genuine understanding rather than memorised facts
Measurement Accuracy: The degree to which a lab measurement reflects the true value of the quantity being measured; affected by instrument error, environmental noise, and sampling bias
Lab Notebook: A structured record of hypotheses, procedures, raw data, and analysis; the primary evidence of scientific rigour in a lab exercise
Pre-Lab Quiz: A short assessment taken before a lab to verify that the student understands the theory needed to conduct the exercise safely and productively
Post-Lab Analysis: The structured interpretation of lab results, connecting measured values to theoretical predictions and explaining discrepancies
Peer Review: Examining another student’s lab report to identify errors, missing steps, and unjustified conclusions — a key skill for professional engineering practice
19.1 In 60 Seconds
This hands-on lab chapter walks you through configuring ESP32 and Arduino devices for Wi-Fi connectivity: connecting to networks, retrieving IP/MAC addresses and signal strength, scanning for nearby access points, implementing reconnection logic, and configuring WPA2/WPA3 security. These are the essential practical skills for getting any IoT device online.
19.2 Learning Objectives
By the end of this chapter, you will be able to:
Configure Wi-Fi Connectivity: Set up ESP32 and Arduino devices for wireless network connections
Retrieve Network Information: Programmatically obtain IP addresses, MAC addresses, and signal strength
Implement Network Scanning: Create tools to discover nearby networks and analyze wireless environments
Debug Connection Issues: Troubleshoot common Wi-Fi configuration problems using serial output
These labs assume you have seen the core networking theory and are now ready to practice on real or simulated networks.
If you have hardware (ESP32/Arduino and home Wi-Fi), focus on the C++ examples and follow the checklists in each lab.
If you do not have hardware or cannot install tools, you can still learn a lot by:
reading the code and comments,
comparing the provided example outputs with what you see on your own laptop or VM,
answering the Knowledge Check questions using the explanations as a guide.
Key terms used throughout this chapter:
Term
Simple explanation
SSID
The name of a Wi-Fi network
Gateway
Router that forwards traffic to other networks
DNS server
Translates names like example.com to IP addresses
RSSI
Received Signal Strength Indicator (Wi-Fi signal)
If you ever feel lost, go back to Networking Basics and Wi-Fi Fundamentals to refresh the concepts, then return here and treat the Python tools as black-box helpers whose outputs you interpret rather than code you must fully understand line-by-line.
19.5 Hands-On: Network Configuration
Time: ~15 min | Level: Intermediate | Ref: P07.C16.U01
Lab network topology showing ESP32 connecting to home network
Figure 19.1: Lab Network Topology: ESP32 IoT device connecting to home network, showing DHCP IP assignment, DNS resolution through gateway router, and internet connectivity. The workflow demonstrates the complete network stack from Wi-Fi association through application-layer HTTP requests, with typical home network addressing (192.168.1.0/24 subnet).
Figure 19.2: Alternative View: Connection Timeline - While the topology diagram shows WHERE data flows, this timeline shows WHEN each step happens during IoT device boot. Layer 2 Wi-Fi association takes 0-1.5 seconds (scanning, authentication, association). Layer 3 IP configuration via DHCP adds another second. Application-layer setup (DNS, TLS, MQTT connect) takes 1.5+ seconds more. Total cold-boot to data-ready: 4+ seconds. Understanding this timeline helps debug connectivity issues and optimize IoT device startup time.
No hardware? No problem! Run this ESP32 Wi-Fi code directly in your browser using the simulator below. Watch the Serial Monitor to see connection status, IP address, MAC address, and signal strength.
What to Try:
Click the green Play button to start the simulation
Watch the Serial Monitor (bottom panel) for connection output
The simulated ESP32 connects to a virtual “Wokwi-GUEST” network
Observe: IP address, MAC address, gateway, subnet, DNS, and RSSI values
Learning Activities:
RSSI Signal Strength: Values from -50 dBm (excellent) to -90 dBm (poor)
MAC Address: Notice the unique hardware identifier format (DC:A6:32:XX:XX:XX = Espressif)
Try modifying: Add WiFi.disconnect() in loop to test reconnection behavior
Lab Extension: Build Your Own Network - With Hardware
Have real hardware? Follow these steps to connect your physical ESP32:
Hardware Needed:
ESP32 development board
USB cable
Wi-Fi network (2.4 GHz – ESP32 does not support 5 GHz!)
Steps:
Flash the ESP32 Wi-Fi example code (above) with your SSID/password
Open Serial Monitor (115200 baud)
Observe IP address assignment via DHCP
Note the gateway and DNS servers
From your computer, ping the ESP32’s IP address
Modify code to ping google.com from ESP32
Challenge: Set a static IP instead of DHCP. Why might this be useful for IoT deployments?
Wi-Fi troubleshooting flowchart for ESP32 connection failures
Figure 19.3: Wi-Fi Troubleshooting Flowchart: Systematic diagnostic process for resolving ESP32 Wi-Fi connection failures. The flowchart covers common issues including incorrect credentials, SSID visibility problems, 2.4 GHz vs 5 GHz band compatibility, WPA2/WPA3 authentication failures, DHCP configuration issues, DNS resolution problems, router firewall rules, and MAC address filtering. Each decision point provides specific debugging steps and code fixes.
Quick Check: ESP32 Network Configuration
19.6 Python Implementations
Production-ready Python tools for network analysis and IoT networking.
19.6.1 IP Address Calculator and Subnet Analyzer
Example Output:
IP Address Analysis
============================================================
IP Address: 192.168.1.100/24
Subnet Mask: 255.255.255.0
Network Address: 192.168.1.0
Broadcast Address: 192.168.1.255
Address Class: Class C
Private Address: Yes
Usable Host Range: 192.168.1.1 - 192.168.1.254
Total Hosts: 256
Usable Hosts: 254
============================================================
IoT Network Planning Example
============================================================
IoT Network: 10.20.28.0/22
Subnet Mask: 255.255.252.0
Usable Hosts: 1022 IoT devices
Usable Range: 10.20.28.1 - 10.20.31.254
Try It: Interactive Subnet Calculator
Adjust the IP address octets and CIDR prefix length to see how the network address, broadcast address, and usable host count change in real time.
Network Device Scanner
============================================================
Scanning 254 addresses in 192.168.1.0/24...
Found: 192.168.1.1 (router.local)
Found: 192.168.1.100 (esp32-sensor.local)
Found: 192.168.1.150 (raspberry-pi.local)
============================================================
Scan Results: 3 devices found
============================================================
Device: 192.168.1.1
Hostname: router.local
Response Time: 2.45 ms
Open Ports: 80, 443
Device: 192.168.1.100
Hostname: esp32-sensor.local
Response Time: 15.67 ms
Open Ports: 80, 1883
Device: 192.168.1.150
Hostname: raspberry-pi.local
Response Time: 8.23 ms
Open Ports: 22, 80, 1883
19.6.3 Protocol Performance Simulator
Example Output:
Transport Protocol Comparison for IoT
======================================================================
Scenario: 100 packets x 100 bytes, 5% packet loss, 20ms latency
TCP Statistics:
Packets Sent: 105
Packets Received: 100
Packets Lost: 5
Delivery Rate: 95.24%
Packet Loss Rate: 4.76%
Total Bytes: 14,700
Avg Latency: 21.0 ms
Throughput: 560.0 Kbps
UDP Statistics:
Packets Sent: 100
Packets Received: 95
Packets Lost: 5
Delivery Rate: 95.0%
Packet Loss Rate: 5.0%
Total Bytes: 12,800
Avg Latency: 20.0 ms
Throughput: 512.0 Kbps
======================================================================
IoT Use Case Recommendations:
======================================================================
Use TCP when:
- Reliability is critical (firmware updates, configuration)
- Data loss is unacceptable (financial transactions)
- Order matters (sequential commands)
- Trade-off: 1.0ms higher latency
Use UDP when:
- Real-time data (sensor readings every second)
- Occasional loss is acceptable (redundant sensors)
- Low latency is critical (voice, video)
- Benefit: 20.0ms latency (1.1x faster)
Try It: TCP vs UDP Performance Explorer
Adjust network conditions to see how TCP and UDP behave differently. Change packet loss rate, base latency, and payload size to understand the trade-offs for IoT applications.
MAC Address Analysis
============================================================
MAC Address: B8:27:EB:12:34:56
OUI: B8:27:EB
NIC: 12:34:56
Vendor: Raspberry Pi Foundation
Type: Unicast
Administration: Universal
MAC Address: DC:A6:32:AB:CD:EF
OUI: DC:A6:32
NIC: AB:CD:EF
Vendor: Espressif (ESP32)
Type: Unicast
Administration: Universal
MAC Address: 00:1B:44:11:22:33
OUI: 00:1B:44
NIC: 11:22:33
Vendor: Arduino
Type: Unicast
Administration: Universal
Try It: MAC Address Analyzer
Enter a MAC address to parse its components. The first 3 bytes (OUI) identify the manufacturer, and the last 3 bytes (NIC) are the device-specific identifier. Try common IoT vendor prefixes like DC:A6:32 (Espressif/ESP32) or B8:27:EB (Raspberry Pi).
Explore how RSSI (Received Signal Strength Indicator) values map to real-world Wi-Fi quality. Drag the distance slider to simulate how signal degrades as an ESP32 moves farther from the access point, and see the impact on IoT data reliability.
Show code
viewof distanceM = Inputs.range([0.5,50], {value:5,step:0.5,label:"Distance from AP (meters)"})viewof wallCount = Inputs.range([0,5], {value:0,step:1,label:"Walls between device and AP"})viewof frequency = Inputs.select(["2.4 GHz","5 GHz"], {value:"2.4 GHz",label:"Wi-Fi Frequency Band"})
19.7.2 Lab 2: Python Advanced Network Scanner with Service Detection
Network scanning workflow for IoT device discovery
Figure 19.4: Network Scanning Workflow: Automated process for discovering IoT devices on a subnet. The scanner parses network ranges (CIDR notation), pings each host to check availability, performs reverse DNS lookups for hostnames, scans common IoT ports (22-SSH, 80-HTTP, 443-HTTPS, 1883-MQTT, 5683-CoAP, 8080-HTTP-Alt, 8883-MQTTS), grabs service banners to identify protocols, and generates security analysis reports highlighting unencrypted services.
Objective: Build a network scanner that identifies IoT devices by detecting open ports and services.
Materials:
Python 3.7+
Local network access
Complete Code:
Expected Output:
Scanning 192.168.1.0/24 for IoT devices...
Checking 254 hosts on 8 ports
======================================================================
Found: 192.168.1.1 (router.local) - 2 ports open
Found: 192.168.1.100 (esp32-sensor.local) - 3 ports open
Found: 192.168.1.150 (raspberry-pi.local) - 4 ports open
======================================================================
Scan Complete: 3 IoT devices found
======================================================================
Device: 192.168.1.1 (router.local)
Services:
Port 80: HTTP - HTTP/1.1 200 OK
Port 443: HTTPS
Device: 192.168.1.100 (esp32-sensor.local)
Services:
Port 80: HTTP - ESP32 Web Server
Port 1883: MQTT
Port 8080: HTTP Alt
Warning: Insecure services detected!
- HTTP (port 80): Consider HTTPS (443)
- MQTT (port 1883): Consider MQTT/TLS (8883)
Device: 192.168.1.150 (raspberry-pi.local)
Services:
Port 22: SSH
Port 80: HTTP
Port 443: HTTPS
Port 1883: MQTT
Warning: Insecure services detected!
- HTTP (port 80): Consider HTTPS (443)
- MQTT (port 1883): Consider MQTT/TLS (8883)
Learning Outcomes:
Perform service detection and port scanning
Identify common IoT protocols
Detect security vulnerabilities
Use concurrent programming for efficiency
Understand service banners
19.8 Additional Visual References
Visual: IoT Networking Stack
IoT networking stack showing protocol layers
Understanding the complete IoT networking stack helps developers see how protocols at different layers interact during device communication.
Visual: Connectivity Metrics
Network connectivity metrics for IoT performance evaluation
Key metrics for evaluating IoT network performance: RSSI for signal quality, latency for responsiveness, throughput for data capacity, and packet loss for reliability.
Visual: Wi-Fi Module Architecture
Wi-Fi module internal architecture
Understanding Wi-Fi module architecture helps developers configure and troubleshoot wireless connectivity in ESP32 and similar IoT platforms.
Visual: Wi-Fi Mesh Network
Wi-Fi mesh network topology
Wi-Fi mesh networks extend coverage beyond single access point range, providing redundant connectivity paths ideal for large IoT deployments.
Visual: 802.11 Channel Access
802.11 CSMA/CA channel access mechanism
The 802.11 CSMA/CA mechanism ensures fair channel access among multiple wireless devices, essential knowledge for debugging Wi-Fi connectivity issues in dense IoT deployments.
Decision Framework: Choosing Static vs DHCP for Production IoT
This decision matrix helps you determine the optimal IP addressing strategy for different IoT device types:
Device Type
Static IP
DHCP
DHCP Reservation
Rationale
MQTT Broker
Best
No
Acceptable
Fixed address required by all clients; DNS adds complexity; static = zero dependencies
IoT Gateway
Best
No
Good
Port forwarding rules need predictable address; reservation provides flexibility + stability
Security Cameras
Acceptable
No
Best
NVR needs stable addresses; reservation enables mass deployment without manual config per camera
Mobile Robots
No
Best
No
Devices roam between APs; dynamic assignment handles mobility; static would require manual changes per zone
Temperature Sensors
No
Best
Optional
100+ sensors = manual config nightmare; DHCP auto-provisions; reservations useful for critical zones only
Industrial PLCs
Required
No
No
Safety-critical control systems must function even if DHCP server fails; static guarantees deterministic addresses
Development/Test Devices
No
Best
No
Frequent additions/removals; DHCP prevents IP conflicts; no production dependencies
Decision Tree:
Is device safety-critical or provides infrastructure service?
+-- YES -> Does it require external port forwarding?
| +-- YES -> Use DHCP Reservation (easy management + stable address)
| +-- NO -> Use Static IP (maximum reliability, zero dependencies)
+-- NO -> Does device count exceed 50?
+-- YES -> Use DHCP (automation essential, manual config unscalable)
+-- NO -> Will device change networks?
+-- YES -> Use DHCP (mobility support)
+-- NO -> Use DHCP Reservation (predictable + manageable)
The dynamic pool is oversubscribed by 4.3x, which works because not all 450 sensors are online simultaneously. With a 10% simultaneous connection rate, only ~45 sensors need DHCP leases at once, fitting comfortably in the 104-address pool. This demonstrates the efficiency of DHCP for large sensor deployments – 450 devices share 104 addresses via lease rotation.
Troubleshooting Decision Table:
Problem
Static IP
DHCP
DHCP Reservation
Device won’t connect
Check IP conflict (ping first), subnet mask, gateway
Check DHCP server status, lease availability
Check MAC address correct in reservation
Intermittent connectivity
Non-issue (address is fixed)
Check lease time (too short?), DHCP server reliability
Check reservation not conflicting with static range
Can’t reach device remotely
Firewall/NAT config issue
Device IP changed – check DHCP logs
Reservation correct but port forwarding not updated
Device moved to new network
Requires manual reconfiguration (firmware update or console access)
Works immediately
Requires new reservation on new network
Key Metrics to Track:
Method
IP Conflict Rate
Time to Provision
Mean Time to Resolve
Static IP
Target < 0.1% (requires tracking spreadsheet)
~10 min (manual config)
~30 min (manual troubleshooting)
DHCP
~0% (server prevents conflicts)
~30 sec (plug in and power on)
~5 min (check DHCP logs)
DHCP Reservation
~0% (managed by DHCP)
~2 min (add MAC reservation, then deploy)
~10 min (verify reservation DB)
Security Implications:
Method
DHCP Snooping
IP Source Guard
DAI Support
MAC Filtering
Static IP
Compatible
Compatible
Compatible
Manual ACLs required
DHCP
Essential
Essential
Essential
MAC changes break reservation
DHCP Reservation
Optimal
Optimal
Optimal
Reservation ties MAC to IP
Best Practice for Production IoT:
Use DHCP with reservations for 80% of devices (security cameras, sensors with known locations, gateways), static IP for 15% (critical infrastructure like brokers, NTP, DNS), and pure DHCP for 5% (test devices, temporary maintenance equipment).
This provides the “best of both worlds”: central management via DHCP server + address predictability via reservations + maximum reliability for critical infrastructure via static.
19.9 Interactive Review Activities
19.9.1 Match IoT Network Concepts
19.9.2 Sequence: ESP32 Cold Boot to Data Ready
Common Pitfalls
1. Memorising Lab Results Without Understanding Them
Writing down measured values without being able to explain why they differ from theoretical predictions scores poorly on post-lab analysis questions. Fix: for every measurement that differs from theory by more than 10%, write one sentence explaining the physical reason for the discrepancy.
2. Completing the Lab and Then Attempting the Quiz Without Reviewing Notes
Lab details fade quickly. Fix: review lab notes and sketched diagrams immediately after completing the lab, before moving on to the quiz.
3. Treating the Quiz as Separate From the Lab
Quiz questions about lab exercises test comprehension of what you observed and why. Generic textbook knowledge without reference to the specific lab measurements earns partial credit only. Fix: answer quiz questions with specific reference to your own lab measurements and observations.
🏷️ Label the Diagram
Code Challenge
19.10 Summary
Wi-Fi connectivity for IoT devices requires configuring SSID credentials, retrieving network parameters (IP address, gateway, DNS), and monitoring connection status using libraries like the ESP32 WiFi.h library
Network information retrieval enables devices to programmatically access IP addresses, MAC addresses, subnet masks, gateway addresses, and signal strength (RSSI) for diagnostics and troubleshooting
IP address calculations involve determining network addresses, broadcast addresses, and usable host ranges using subnet masks, with the formula: usable hosts = 2^(32 - prefix) - 2
Network scanning discovers active devices on a subnet by probing ports and services, identifying IoT protocols like MQTT (1883), CoAP (5683), HTTP (80/443), and SSH (22) to map network topology
Protocol performance varies significantly between TCP and UDP, with TCP providing reliable delivery through retransmissions at the cost of higher latency, while UDP offers lower latency with potential packet loss
MAC address analysis reveals device manufacturers through OUI (Organizationally Unique Identifier) lookups and identifies address types (unicast vs multicast, universal vs locally administered)
Security considerations include detecting insecure services (Telnet, unencrypted HTTP/MQTT), implementing TLS encryption (HTTPS on 443, MQTT/TLS on 8883), and proper firewall configuration
IP addressing strategy (static, DHCP, or DHCP reservations) should match device criticality, deployment scale, and mobility requirements
19.11 What’s Next
After completing these hands-on labs and quizzes, you are ready to explore more advanced networking topics and protocols:
Advanced ESP32 Wi-Fi projects including OTA updates, WPA3, Wi-Fi provisioning, and mesh networking
19.12 Knowledge Check
Test your understanding of network configuration, addressing, scanning, and protocol performance with these questions.
Auto-Gradable Quick Check
Understanding Check: Wi-Fi Troubleshooting for ESP32 Fleet
Scenario: You have deployed 50 ESP32 environmental monitors across a 3-story office building. After 2 weeks, 15 devices (30%) stop connecting to Wi-Fi. The others work fine.
Initial Assumptions (All Wrong):
“Wi-Fi password must have changed” – No, 35 devices still connect fine
“ESP32 Wi-Fi is unreliable” – No, same hardware works elsewhere
“Interference from new equipment” – No, happens on all floors randomly
Systematic Troubleshooting (Flowchart-Based):
Step 1: Can ESP32 see network? Run WiFi.scanNetworks() on failed device – Found 12 networks, including target SSID
A technician configured 15 replacement ESP32s with the visible 5 GHz SSID
ESP32 sees 5 GHz beacons but cannot associate (hardware limitation: 2.4 GHz radio only)
The Fix:
// BEFORE (fails silently)constchar* ssid ="Office_5GHz";// AFTER (explicit 2.4 GHz with validation)constchar* ssid ="Office_2.4GHz";WiFi.begin(ssid, password);// Add diagnostic feedbackif(WiFi.status()!= WL_CONNECTED){ Serial.println("Wi-Fi failed!"); Serial.print("Attempted SSID: "); Serial.println(ssid); Serial.println("Ensure router has 2.4 GHz band enabled.");}
Lessons Learned:
ESP32 limitation: Standard ESP32 supports 2.4 GHz only (no 5 GHz, no Wi-Fi 6E)
Dual-band confusion: Devices see 5 GHz beacons but cannot decode/associate with them
Silent failure: No error message from the library, just a connection timeout
Diagnostic value: WiFi.scanNetworks() reveals what the device sees vs what it can use
Design Principle: Always verify device Wi-Fi capabilities before deployment. Document which SSIDs are 2.4 GHz vs 5 GHz. Add runtime diagnostics to IoT firmware for remote troubleshooting.
Question 1: Subnet Mask Calculation
A network has IP 192.168.10.0 with subnet mask 255.255.255.192 (/26). How many usable host addresses are available, and what is the broadcast address?
10.0.0.0/8 (16+ million addresses) – Large enterprises, smart cities
172.16.0.0/12 (1+ million addresses) – Medium organizations
192.168.0.0/16 (65,536 addresses) – Home networks, small buildings
NAT (Network Address Translation) allows private devices to access the internet by sharing a single public IP. However, NAT creates challenges for IoT: - Inbound connections are blocked (devices behind NAT cannot be directly reached) - Solutions: MQTT persistent connections, port forwarding, VPN tunnels
Question 3: Default Gateway Role
What is the role of a default gateway, and why is it essential for IoT devices to reach cloud servers?
Answer:
The default gateway is the router that forwards packets from local network devices to other networks (including the internet). When an IoT device needs to send data to a cloud server:
Device checks: “Is destination IP on my local subnet?” (using subnet mask)
If remote (different subnet): Send packet to default gateway
Gateway examines destination IP and forwards toward the target network
Packet may traverse multiple routers before reaching cloud server
Example:
IoT sensor IP: 192.168.1.100/24
Default gateway: 192.168.1.1
Cloud server: 54.235.100.42
The sensor’s subnet mask (255.255.255.0) reveals that 54.235.100.42 is NOT in the 192.168.1.0/24 network, so the packet must go to the gateway.
IoT configuration essentials:
IP address (device identity)
Subnet mask (local network boundary)
Default gateway (exit point for remote destinations)
DNS server (resolve hostnames like mqtt.example.com)
Question 4: Port Numbers for IoT Protocols
What port numbers do common IoT protocols use, and why are they important?
Answer:
Port numbers identify specific services running on a device. Key IoT protocol ports:
Protocol
Port
Transport
Usage
MQTT
1883
TCP
Unencrypted messaging
MQTT/TLS
8883
TCP
Encrypted messaging
CoAP
5683
UDP
Constrained devices
CoAP/DTLS
5684
UDP
Secure constrained devices
HTTP
80
TCP
Web interfaces
HTTPS
443
TCP
Secure web
SSH
22
TCP
Remote device access
Modbus TCP
502
TCP
Industrial control
Why ports matter for IoT:
Firewall rules: Must allow traffic on required ports (e.g., open 8883 for secure MQTT)
Security scanning: Open ports reveal services; close unnecessary ones
Service identification: Port 1883 open suggests MQTT broker
Troubleshooting: Connection issues often relate to blocked ports
Security note: Always prefer encrypted variants (8883 over 1883, 5684 over 5683) in production deployments.