19  Networking: Labs and Quiz

Key Concepts
  • 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
  • Apply Security Settings: Configure WPA2/WPA3 credentials for secure IoT device connectivity
  • Monitor Network Status: Implement connection event handlers and reconnection logic

19.3 Prerequisites

Before starting these labs, you will get the most value if you are comfortable with:

If any of these feel unfamiliar, skim the referenced chapters first and then return here for hands-on practice.

Deep Dives:

Comparisons:

Hands-On:

Learning:

19.4 Getting Started (For Beginners)

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 diagram showing an ESP32 IoT device connecting to a home Wi-Fi network, with DHCP IP assignment from the router, DNS resolution through the gateway, and internet connectivity. The network uses a typical 192.168.1.0/24 subnet with the complete path from Wi-Fi association through application-layer HTTP requests.

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).
Timeline diagram showing ESP32 network connection phases. Layer 2 Wi-Fi Association (0-1500ms): scan SSIDs and receive beacons (0-500ms), authentication WPA2 exchange (500-1000ms), association MAC registered with AP (1000-1500ms). Layer 3 IP Configuration (1500-2500ms): DHCP Discover broadcast (1500-2000ms), DHCP Offer/Request/ACK with IP 192.168.1.100 assigned (2000-2500ms). Layer 7 Application Ready (2500ms+): DNS query to resolve hostname (2500-3000ms), TCP/TLS handshake for secure connection (3000-4000ms), MQTT Connect ready to publish data (4000ms+).
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.

19.5.1 Example 1: ESP32 Wi-Fi Connection

// ESP32 Wi-Fi Setup
#include <WiFi.h>

const char* ssid = "YourNetworkName";
const char* password = "YourPassword";

void setup() {
    Serial.begin(115200);

    // Connect to Wi-Fi
    WiFi.begin(ssid, password);
    Serial.print("Connecting to Wi-Fi");

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("\nConnected!");

    // Print network information
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());

    Serial.print("MAC Address: ");
    Serial.println(WiFi.macAddress());

    Serial.print("Gateway: ");
    Serial.println(WiFi.gatewayIP());

    Serial.print("Subnet Mask: ");
    Serial.println(WiFi.subnetMask());

    Serial.print("DNS: ");
    Serial.println(WiFi.dnsIP());

    Serial.print("RSSI (Signal Strength): ");
    Serial.print(WiFi.RSSI());
    Serial.println(" dBm");
}

void loop() {
    // Your IoT application code here
}
Try It: Interactive ESP32 Wi-Fi Simulator

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:

  1. Click the green Play button to start the simulation
  2. Watch the Serial Monitor (bottom panel) for connection output
  3. The simulated ESP32 connects to a virtual “Wokwi-GUEST” network
  4. 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:

  1. Flash the ESP32 Wi-Fi example code (above) with your SSID/password
  2. Open Serial Monitor (115200 baud)
  3. Observe IP address assignment via DHCP
  4. Note the gateway and DNS servers
  5. From your computer, ping the ESP32’s IP address
  6. Modify code to ping google.com from ESP32

Challenge: Set a static IP instead of DHCP. Why might this be useful for IoT deployments?

Systematic Wi-Fi troubleshooting flowchart for ESP32 connection failures. Decision points cover 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 branch provides specific debugging steps and code fixes.

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.

19.6.2 Network Device Scanner

Example Output:

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.

19.6.4 MAC Address Analyzer

Example Output:

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).

19.7 Hands-On Labs

19.7.1 Lab 1: ESP32 Network Diagnostics Dashboard

Objective: Create a comprehensive network diagnostics tool on ESP32 that reports all network parameters.

Materials:

  • ESP32 development board
  • Wi-Fi network
  • Serial monitor

Complete Code:

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

unsigned long lastDiagnostic = 0;
const long diagnosticInterval = 10000; // Every 10 seconds

void printSeparator() {
    for (int i = 0; i < 60; i++) Serial.print("=");
    Serial.println();
}

void printNetworkDiagnostics() {
    Serial.println();
    printSeparator();
    Serial.println("ESP32 Network Diagnostics Report");
    printSeparator();

    // Wi-Fi Status
    Serial.println("\n1. Wi-Fi Connection:");
    Serial.print("   Status: ");
    Serial.println(WiFi.status() == WL_CONNECTED ? "Connected" : "Disconnected");
    Serial.print("   SSID: ");
    Serial.println(WiFi.SSID());
    Serial.print("   RSSI: ");
    Serial.print(WiFi.RSSI());
    Serial.print(" dBm (");

    int rssi = WiFi.RSSI();
    if (rssi > -50) Serial.print("Excellent");
    else if (rssi > -60) Serial.print("Good");
    else if (rssi > -70) Serial.print("Fair");
    else Serial.print("Poor");
    Serial.println(")");

    Serial.print("   Channel: ");
    Serial.println(WiFi.channel());

    // IP Configuration
    Serial.println("\n2. IP 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());

    // MAC Address
    Serial.println("\n3. Hardware:");
    Serial.print("   MAC Address: ");
    Serial.println(WiFi.macAddress());

    // Calculate subnet info
    IPAddress ip = WiFi.localIP();
    IPAddress subnet = WiFi.subnetMask();

    // Network address
    IPAddress network(ip[0] & subnet[0], ip[1] & subnet[1],
                     ip[2] & subnet[2], ip[3] & subnet[3]);

    Serial.println("\n4. Network Information:");
    Serial.print("   Network Address: ");
    Serial.println(network);

    // Broadcast address
    IPAddress broadcast(ip[0] | ~subnet[0], ip[1] | ~subnet[1],
                       ip[2] | ~subnet[2], ip[3] | ~subnet[3]);
    Serial.print("   Broadcast Address: ");
    Serial.println(broadcast);

    // Test connectivity
    Serial.println("\n5. Connectivity Tests:");

    // Gateway reachability check
    Serial.print("   Gateway Reachable: ");
    bool gatewayReachable = WiFi.gatewayIP() != IPAddress(0, 0, 0, 0);
    Serial.println(gatewayReachable ? "Yes" : "No");

    // DNS test
    Serial.print("   DNS Resolution: ");
    IPAddress result;
    int dnsResult = WiFi.hostByName("www.google.com", result);
    if (dnsResult == 1) {
        Serial.print("Working (google.com = ");
        Serial.print(result);
        Serial.println(")");
    } else {
        Serial.println("Failed");
    }

    // Internet connectivity test
    Serial.print("   Internet Access: ");
    HTTPClient http;
    http.setTimeout(2000);
    http.begin("http://clients3.google.com/generate_204");
    int httpCode = http.GET();
    Serial.println(httpCode == 204 ? "Yes" : "No");
    http.end();

    Serial.println();
    printSeparator();
}

void setup() {
    Serial.begin(115200);
    delay(1000);

    Serial.println("\nESP32 Network Diagnostics Tool");
    Serial.println("Connecting to Wi-Fi...");

    WiFi.begin(ssid, password);

    int attempts = 0;
    while (WiFi.status() != WL_CONNECTED && attempts < 20) {
        delay(500);
        Serial.print(".");
        attempts++;
    }

    if (WiFi.status() == WL_CONNECTED) {
        Serial.println("\nWi-Fi Connected!");
        printNetworkDiagnostics();
    } else {
        Serial.println("\nWi-Fi Connection Failed!");
    }
}

void loop() {
    unsigned long now = millis();

    if (now - lastDiagnostic >= diagnosticInterval) {
        lastDiagnostic = now;

        if (WiFi.status() == WL_CONNECTED) {
            printNetworkDiagnostics();
        } else {
            Serial.println("Wi-Fi Disconnected - Attempting reconnection...");
            WiFi.reconnect();
        }
    }
}

Expected Output:

============================================================
ESP32 Network Diagnostics Report
============================================================

1. Wi-Fi Connection:
   Status: Connected
   SSID: MyHomeNetwork
   RSSI: -45 dBm (Excellent)
   Channel: 6

2. IP Configuration:
   IP Address: 192.168.1.100
   Subnet Mask: 255.255.255.0
   Gateway: 192.168.1.1
   DNS: 192.168.1.1

3. Hardware:
   MAC Address: DC:A6:32:AB:CD:EF

4. Network Information:
   Network Address: 192.168.1.0
   Broadcast Address: 192.168.1.255

5. Connectivity Tests:
   Gateway Reachable: Yes
   DNS Resolution: Working (google.com = 172.217.14.206)
   Internet Access: Yes

============================================================

Learning Outcomes:

  • Retrieve all network configuration parameters
  • Perform connectivity diagnostics
  • Understand Wi-Fi signal strength (RSSI)
  • Calculate network and broadcast addresses
  • Test DNS resolution and internet connectivity
Try It: Wi-Fi RSSI Signal Strength Visualizer

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.


19.7.2 Lab 2: Python Advanced Network Scanner with Service Detection

Network scanning workflow diagram showing the automated process for discovering IoT devices on a subnet. The scanner parses network ranges in 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.

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

Complete IoT networking stack diagram showing Physical, Data Link, Network, Transport, and Application layers with common IoT protocols at each level including Wi-Fi, Ethernet, 6LoWPAN at the link layer, IPv4/IPv6 at the network layer, TCP/UDP at the transport layer, and MQTT/CoAP/HTTP at the application layer.

IoT networking stack showing protocol layers

Understanding the complete IoT networking stack helps developers see how protocols at different layers interact during device communication.

Network connectivity metrics diagram showing RSSI signal strength ranges, latency measurement, throughput calculation, and packet loss percentages for evaluating IoT network performance in different deployment scenarios.

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.

Wi-Fi module architecture diagram showing the ESP32 or similar IoT Wi-Fi module with antenna, RF front-end, baseband processor, MAC layer, and SPI/UART interface connections to the host microcontroller.

Wi-Fi module internal architecture

Understanding Wi-Fi module architecture helps developers configure and troubleshoot wireless connectivity in ESP32 and similar IoT platforms.

Wi-Fi mesh network topology showing multiple access points interconnected wirelessly to extend coverage, with IoT devices connecting to the nearest access point and traffic routing through the mesh for redundancy.

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.

Wi-Fi 802.11 channel access diagram showing the CSMA/CA mechanism with carrier sensing, random backoff timer, data transmission, and acknowledgment timing for collision avoidance in shared wireless medium.

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.

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)

Configuration Examples:

Static IP (ESP32):

IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("Static IP configuration failed");
}
WiFi.begin(ssid, password);

DHCP (ESP32 default):

WiFi.begin(ssid, password);  // DHCP automatic

DHCP Reservation (router config – example for UniFi):

{
  "mac": "DC:A6:32:AB:CD:EF",
  "ip": "192.168.1.100",
  "name": "esp32-sensor-room-301"
}

Hybrid Strategy for Real Deployments:

Building Automation Example (500 devices):

Range IP Addresses Purpose
Static 192.168.10.1 – 192.168.10.50 Gateway (.1), MQTT broker (.10), NTP server (.11), Backup gateway (.2)
DHCP Reservation 192.168.10.51 – 192.168.10.150 Security cameras (.51-.70), Access control panels (.71-.80), HVAC controllers (.81-.95)
DHCP Dynamic Pool 192.168.10.151 – 192.168.10.254 Temperature sensors (400+), Development devices, Guest maintenance laptops

For a 500-device building automation deployment using 192.168.10.0/24:

Address allocation math: $ = 2^8 = 256 $ $ = 256 - 2 = 254 $ $ = 50, (1-50) $ $ = 100, (51-150) $ $ = 104, (151-254) $

IP address utilization: $ = 4, = = 8% $ $ = 45, = = 45% $ $ = 450, = % $

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

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.

Lab details fade quickly. Fix: review lab notes and sketched diagrams immediately after completing the lab, before moving on to the quiz.

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.

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:

Topic Chapter Description
Network Mechanisms Network Mechanisms Packet switching, datagrams, bandwidth vs throughput, and converged network architectures
Layered Network Models Layered Network Models OSI and TCP/IP models, encapsulation processes, and how different layers interact in real IoT systems
Routing Fundamentals Routing Fundamentals How routers make forwarding decisions, routing protocols, and path selection algorithms
MQTT Protocol MQTT Fundamentals Publish-subscribe messaging for IoT: topics, QoS levels, brokers, and when to use MQTT vs other protocols
Transport Layer Transport Fundamentals TCP vs UDP trade-offs in depth, flow control, congestion avoidance, and protocol selection for IoT use cases
Wi-Fi Implementations Wi-Fi IoT Implementations 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.

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

Step 2: Correct password? Check code: const char* password = "OfficeWiFi2024!"Matches router

Step 3: 2.4 GHz network? Router shows: “Office_5GHz” and “Office_2.4GHz” – Failed devices use “Office_5GHz”

Root Cause Found: 15 ESP32s were configured with:

const char* ssid = "Office_5GHz";  // ESP32 does not support 5 GHz!

35 working devices had:

const char* ssid = "Office_2.4GHz";  // Correct 2.4 GHz SSID

Why This Happened:

  • IT upgraded office Wi-Fi, adding a 5 GHz band
  • New “Office_5GHz” SSID advertised prominently
  • 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)
const char* ssid = "Office_5GHz";

// AFTER (explicit 2.4 GHz with validation)
const char* ssid = "Office_2.4GHz";
WiFi.begin(ssid, password);

// Add diagnostic feedback
if (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:

  1. ESP32 limitation: Standard ESP32 supports 2.4 GHz only (no 5 GHz, no Wi-Fi 6E)
  2. Dual-band confusion: Devices see 5 GHz beacons but cannot decode/associate with them
  3. Silent failure: No error message from the library, just a connection timeout
  4. 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.

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?

Answer:

Calculation steps:

  1. Subnet mask analysis: 255.255.255.192 = /26 (26 network bits, 6 host bits)
  2. Total addresses: 2^6 = 64 addresses per subnet
  3. Usable hosts: 64 - 2 = 62 usable host addresses (subtract network and broadcast)
  4. Subnet increment: 256 - 192 = 64

For 192.168.10.0/26:

  • Network address: 192.168.10.0
  • First usable host: 192.168.10.1
  • Last usable host: 192.168.10.62
  • Broadcast address: 192.168.10.63

This subnet size is ideal for small IoT deployments like a single building floor with 50-60 sensors.

Why do most IoT devices use private IP addresses (192.168.x.x, 10.x.x.x) instead of public IPs?

Answer:

Private IP addresses are used for IoT devices because:

  1. Address scarcity: Only ~4.3 billion IPv4 public addresses exist globally, far fewer than the billions of IoT devices
  2. Security: Private IPs are not directly routable from the internet, providing a basic firewall
  3. Cost: Public IPs require registration and often cost money from ISPs
  4. Network flexibility: Private ranges allow organizations to design internal addressing freely

Private IP ranges (RFC 1918):

  • 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

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:

  1. Device checks: “Is destination IP on my local subnet?” (using subnet mask)
  2. If remote (different subnet): Send packet to default gateway
  3. Gateway examines destination IP and forwards toward the target network
  4. 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)

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.