Chapter 80: DHCP Client Implementation

Chapter Objectives

Upon completing this chapter, you will be able to:

  • Understand the fundamental purpose and benefits of the Dynamic Host Configuration Protocol (DHCP).
  • Describe the four-step DHCP DORA process for IP address acquisition.
  • Configure an ESP32 device to act as a DHCP client using the ESP-IDF v5.x framework.
  • Register and handle DHCP-related network events to monitor IP address status.
  • Explain the significance of DHCP options, such as DNS servers and lease times.
  • Troubleshoot common issues encountered during DHCP client implementation.

Introduction

In the previous chapters, we explored how devices communicate using IPv4 and IPv6 addresses, and how these addresses can be manually assigned (static IP). While static IP is suitable for specific scenarios, manually configuring every networked device, especially in large or dynamic environments, is cumbersome and prone to errors. This is where the Dynamic Host Configuration Protocol (DHCP) becomes indispensable.

DHCP automates the process of assigning IP addresses and other network configuration parameters to devices. For embedded systems like the ESP32, integrating a DHCP client simplifies deployment, reduces configuration overhead, and ensures seamless connectivity in most modern network infrastructures. This chapter will delve into the mechanics of DHCP, its implementation on ESP32 using ESP-IDF v5.x, and best practices for robust dynamic IP address acquisition.

Theory

1. What is DHCP?

DHCP (Dynamic Host Configuration Protocol) is a network management protocol used on Internet Protocol (IP) networks for dynamically assigning IP addresses and other communication parameters to devices connected to the network. It operates at the Application Layer of the TCP/IP model, typically using UDP ports 67 (server) and 68 (client).

Analogy: Imagine a new student arriving at a large university. Instead of manually filling out forms for a room number, meal plan, and class schedule, they go to a central “Student Services” office. This office (the DHCP server) automatically assigns them a dorm room (IP address), provides a campus map (subnet mask), tells them where the main gate is (default gateway), and lists important phone numbers (DNS servers). This automated process is much more efficient than manual assignment.

2. Why Use DHCP?

Using DHCP offers significant advantages, especially for embedded systems:

  • Automation: Eliminates manual IP configuration, reducing human error and deployment time.
  • Centralized Management: IP addresses are managed from a central server, making it easy to track and update network configurations.
  • Flexibility: Devices can move between different network segments and automatically obtain new, valid IP configurations.
  • Efficient IP Address Utilization: IP addresses are leased for a specific duration. When a device disconnects or its lease expires, the address can be reclaimed and reused, preventing address exhaustion in networks with many transient devices.

3. The DHCP Process (DORA)

The DHCP client-server interaction typically follows a four-step process known by the acronym DORA:

  1. Discover (DHCP Discover):
    • The DHCP client (e.g., your ESP32) broadcasts a DHCP Discover message on the network. This message is sent to find any available DHCP servers. Since the client doesn’t have an IP address yet, it uses a source IP of 0.0.0.0 and a destination broadcast IP of 255.255.255.255.
    • The message includes the client’s MAC address so that servers can identify it.
  2. Offer (DHCP Offer):
    • Any DHCP server that receives the DHCP Discover message and has an available IP address will send a DHCP Offer message back to the client.
    • This offer includes a proposed IP address, subnet mask, lease time, and the IP address of the offering DHCP server.
  3. Request (DHCP Request):
    • The client receives one or more DHCP Offer messages. It selects one of the offers (usually the first one received) and sends a DHCP Request message.
    • This request is a broadcast to inform all other DHCP servers that it has accepted an offer from a specific server, and to implicitly decline other offers. It explicitly identifies the chosen server.
  4. Acknowledge (DHCP ACK):
    • The selected DHCP server receives the DHCP Request and sends a DHCP ACK (Acknowledgement) message back to the client.
    • This message confirms the IP address assignment and provides all the necessary network configuration parameters, including the IP address, subnet mask, default gateway, DNS server addresses, and the final lease time.
    • Upon receiving the ACK, the client configures its network interface with the provided information.
%%{init: {"theme": "base", "themeVariables": {"primaryTextColor": "#333333", "lineColor": "#777777", "actorBorder": "#5B21B6"}}}%%
sequenceDiagram;
    participant Client as ESP32 (DHCP Client);
    participant Server as Router/Server (DHCP Server);

    rect rgb(253, 244, 255)
    Note over Client, Server: Initial State: Client needs IP Configuration
    end

    Client->>+Server: 1. DHCPDISCOVER (Broadcast)<br>Src IP: 0.0.0.0, Dst IP: 255.255.255.255<br>Client MAC: XX:XX:XX:XX:XX:XX<br>"Looking for DHCP Server";
    
    Server-->>-Client: 2. DHCPOFFER (Unicast/Broadcast to Client MAC)<br>Offered IP: 192.168.1.100<br>Subnet Mask: 255.255.255.0<br>Lease Time: 86400s<br>Server ID: 192.168.1.1<br>"I have an IP for you";
    
    Client->>+Server: 3. DHCPREQUEST (Broadcast)<br>Client MAC: XX:XX:XX:XX:XX:XX<br>Requested IP: 192.168.1.100<br>Server ID: 192.168.1.1 (Chosen Server)<br>"I accept your offer, Server 192.168.1.1";
    
    Server-->>-Client: 4. DHCPACK (Unicast/Broadcast to Client MAC)<br>Assigned IP: 192.168.1.100<br>Subnet Mask: 255.255.255.0<br>Gateway: 192.168.1.1<br>DNS: 8.8.8.8<br>Lease Time: 86400s<br>"Confirmed. Here are your details.";

    rect rgb(236, 253, 245)
    Note over Client, Server: Client configures interface with received parameters.
    end

4. DHCP Lease Time

When a DHCP server assigns an IP address, it’s not permanent. It’s a lease for a specific duration, defined by the lease time.

  • Purpose: Allows IP addresses to be reclaimed and reused if a device disconnects or no longer needs the address, preventing address exhaustion.
  • Renewal: Before the lease expires (typically at 50% of the lease time), the client will attempt to renew its lease with the same DHCP server. If successful, the lease time is reset.
  • Rebinding: If the client fails to renew with the original server, it will attempt to rebind (broadcast a request) to any available DHCP server at a later point (e.g., 87.5% of the lease time).
  • Expiration: If the lease cannot be renewed or rebound, the IP address expires, and the client must stop using it and restart the DORA process.
%%{init: {"theme": "base", "themeVariables": {"primaryTextColor": "#333333", "lineColor": "#777777"}}}%%
stateDiagram-v2
    
    [*] --> INIT : Client Starts

    INIT : <b>INIT</b><br/>No IP Address
    INIT --> DISCOVERING : Sends DHCPDISCOVER

    DISCOVERING : <b>DISCOVERING</b><br/>Waiting for DHCPOFFER
    DISCOVERING --> REQUESTING : Receives DHCPOFFER(s), Selects one
    DISCOVERING --> INIT : Timeout / No Offers

    REQUESTING : <b>REQUESTING</b><br/>Sends DHCPREQUEST for selected offer
    REQUESTING --> BOUND : Receives DHCPACK
    REQUESTING --> INIT : Receives DHCPNAK / Timeout

    BOUND : <b>BOUND</b><br/>IP Address Leased & Usable
    BOUND --> RENEWING : T1 Timer Expires (50% Lease Time)
    BOUND --> REBINDING : T2 Timer Expires (87.5% Lease Time)<br/>If Renewal Failed
    BOUND --> INIT : Lease Expires / User Releases

    RENEWING : <b>RENEWING</b><br/>Sends DHCPREQUEST (Unicast to original server)
    RENEWING --> BOUND : Receives DHCPACK (Lease Extended)
    RENEWING --> REBINDING : Fails to renew with original server / T2 Reached

    REBINDING : <b>REBINDING</b><br/>Sends DHCPREQUEST (Broadcast to any server)
    REBINDING --> BOUND : Receives DHCPACK (New Lease from any server)
    REBINDING --> INIT : Fails to rebind / Lease Expires

    classDef initState fill:#FEE2E2,stroke:#DC2626,color:#991B1B
    classDef discoveringState fill:#FEF3C7,stroke:#D97706,color:#92400E
    classDef requestingState fill:#FEF3C7,stroke:#D97706,color:#92400E
    classDef boundState fill:#D1FAE5,stroke:#059669,color:#065F46
    classDef renewingState fill:#DBEAFE,stroke:#2563EB,color:#1E40AF
    classDef rebindingState fill:#DBEAFE,stroke:#2563EB,color:#1E40AF

    class INIT initState
    class DISCOVERING discoveringState
    class REQUESTING requestingState
    class BOUND boundState
    class RENEWING renewingState
    class REBINDING rebindingState

5. DHCP Options

Beyond just the IP address, DHCP servers can provide clients with a variety of other network configuration parameters, known as DHCP options. Common options include:

Option Number Option Name Description Example Value
1 Subnet Mask Defines the network and host portions of the client’s IP address. 255.255.255.0
3 Router (Default Gateway) IP address of the default gateway router for the client to use. 192.168.1.1
6 Domain Name Server (DNS) IP addresses of DNS servers the client should use for name resolution. Multiple can be provided. 8.8.8.8, 1.1.1.1
15 Domain Name The DNS domain name that the client should use when resolving hostnames. example.com
42 Network Time Protocol (NTP) Servers IP addresses of NTP servers for time synchronization. pool.ntp.org (resolves to IPs)
51 IP Address Lease Time The duration (in seconds) for which the assigned IP address is valid. 86400 (24 hours)
53 DHCP Message Type Indicates the type of DHCP message (Discover, Offer, Request, ACK, NAK, Release, etc.). 1 (Discover), 2 (Offer), …
54 Server Identifier The IP address of the DHCP server that sent the message. 192.168.1.1
  • Subnet Mask: Defines the network and host portions of the IP address.
  • Default Gateway: The IP address of the router for internet access.
  • DNS Servers: IP addresses of Domain Name System servers for hostname resolution.
  • Domain Name: The DNS domain name for the client.
  • NTP Servers: Network Time Protocol servers for time synchronization.

6. DHCP Client vs. Server

  • DHCP Client: A device (like your ESP32) that requests and obtains IP configuration from a DHCP server.
  • DHCP Server: A device (typically a router or a dedicated server) that manages a pool of IP addresses and leases them out to clients.

Practical Examples

This example demonstrates a basic ESP32 DHCP client implementation using Wi-Fi. The ESP-IDF’s esp_netif component handles the DHCP client functionality largely automatically when a default network interface is created. We will focus on event handling to observe the DHCP process.

1. Project Setup

Create a new ESP-IDF project using VS Code. You can use the “ESP-IDF: New Project” command. Name it dhcp_client_example.

2. main/dhcp_client_example_main.c

C
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "sdkconfig.h"

static const char *TAG = "DHCP_CLIENT";

// Event handler for Wi-Fi and IP events
static void event_handler(void *arg, esp_event_base_t event_base,
                          int32_t event_id, void *event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        ESP_LOGI(TAG, "Wi-Fi STA started, connecting...");
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        ESP_LOGI(TAG, "Wi-Fi STA disconnected, retrying connection...");
        esp_wifi_connect(); // Retry connection
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
        ESP_LOGI(TAG, "DHCP: Successfully obtained IPv4 address!");
        ESP_LOGI(TAG, "IP: " IPSTR, IP2STR(&event->ip_info.ip));
        ESP_LOGI(TAG, "Netmask: " IPSTR, IP2STR(&event->ip_info.netmask));
        ESP_LOGI(TAG, "Gateway: " IPSTR, IP2STR(&event->ip_info.gw));

        // You can also retrieve DNS server information
        esp_netif_dns_info_t dns_info[2];
        if (esp_netif_get_dns_info(event->esp_netif, ESP_NETIF_DNS_MAIN, &dns_info[0]) == ESP_OK) {
            ESP_LOGI(TAG, "DNS Primary: " IPSTR, IP2STR(&dns_info[0].ip.u_addr.ip4));
        }
        if (esp_netif_get_dns_info(event->esp_netif, ESP_NETIF_DNS_BACKUP, &dns_info[1]) == ESP_OK) {
            ESP_LOGI(TAG, "DNS Secondary: " IPSTR, IP2STR(&dns_info[1].ip.u_addr.ip4));
        }
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) {
        ESP_LOGW(TAG, "DHCP: Lost IPv4 address!");
        // This event can occur if the lease expires or the network changes.
        // The Wi-Fi driver will typically attempt to reconnect and re-acquire.
    }
}

void app_main(void)
{
    // 1. Initialize NVS (Non-Volatile Storage)
    // NVS is used by Wi-Fi for storing configuration data.
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase()); // Erase NVS if it's full or version mismatch
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 2. Initialize TCP/IP network interface (esp_netif)
    // This initializes the LwIP stack and its components.
    ESP_ERROR_CHECK(esp_netif_init());

    // 3. Create default event loop
    // The event loop is essential for handling asynchronous events like Wi-Fi and IP events.
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    // 4. Create Wi-Fi station interface with default DHCP client enabled
    // esp_netif_create_default_wifi_sta() creates a network interface for Wi-Fi
    // station mode and automatically enables the DHCP client on it.
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif); // Ensure the interface was created successfully

    // 5. Register event handlers
    // We register handlers for Wi-Fi events (connection status) and IP events (IP address acquisition).
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_LOST_IP, &event_handler, NULL));

    // 6. Initialize Wi-Fi driver
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    // 7. Configure Wi-Fi station mode credentials
    wifi_config_t wifi_config = {
        .sta = {
            .ssid = CONFIG_WIFI_SSID,       // Wi-Fi SSID from menuconfig
            .password = CONFIG_WIFI_PASSWORD, // Wi-Fi password from menuconfig
            .threshold.authmode = WIFI_AUTH_WPA2_PSK, // Recommended authentication mode
            .sae_pwe_h2e = WIFI_SAE_MODE_OWE, // For WPA3, if supported by AP
            .sae_h2e_identifier = "",
        },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    
    // 8. Start Wi-Fi
    // This initiates the Wi-Fi connection process, which in turn triggers DHCP.
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "DHCP client initialized. Waiting for IP address...");

    // Application can continue running other tasks here
    // For example, a loop to keep the main task alive
    while (1) {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

3. main/CMakeLists.txt

The default CMakeLists.txt should be sufficient. Ensure idf_component_register is present.

Plaintext
# In the main/CMakeLists.txt file
idf_component_register(SRCS "dhcp_client_example_main.c"
                       INCLUDE_DIRS ".")

4. main/Kconfig.projbuild

This file allows you to configure project-specific settings via idf.py menuconfig.

Create main/Kconfig.projbuild and add the following:

Plaintext
menu "Wi-Fi Configuration"
    config WIFI_SSID
        string "Wi-Fi SSID"
        default "YOUR_SSID"
        help
            SSID of your Wi-Fi network.

    config WIFI_PASSWORD
        string "Wi-Fi Password"
        default "YOUR_PASSWORD"
        help
            Password of your Wi-Fi network.
endmenu

5. Build Instructions

  1. Open VS Code: Open your dhcp_client_example project folder in VS Code.
  2. Configure with menuconfig:
    • Press Ctrl+Shift+P (or Cmd+Shift+P on macOS) to open the command palette.
    • Type and select “ESP-IDF: SDK Configuration Editor (menuconfig)”.
    • Navigate to “Wi-Fi Configuration”.
    • Enter your Wi-Fi SSID and Password.
    • Ensure DHCP client is enabled: Navigate to Component config -> LWIP -> Enable DHCP client. (This is usually enabled by default when using esp_netif_create_default_wifi_sta(), but it’s good to verify).
    • Save the configuration and exit menuconfig.
  3. Build the Project:
    • Open the VS Code Terminal (Terminal > New Terminal).
    • Run idf.py build. This will compile the project.

6. Run/Flash/Observe Steps

  1. Connect Hardware:
    • Connect your ESP32 development board to your computer via USB.
    • Ensure your Wi-Fi router has a DHCP server enabled and is providing network access.
  2. Flash the Firmware:
    • In the VS Code Terminal, run idf.py flash. This will erase the chip and flash your compiled firmware.
  3. Monitor Serial Output:
    • After flashing, run idf.py monitor. This will open the serial monitor and display the logs from your ESP32.

Expected Output:

You should see log messages similar to this:

Plaintext
I (XXX) DHCP_CLIENT: DHCP client initialized. Waiting for IP address...
I (XXX) DHCP_CLIENT: Wi-Fi STA started, connecting...
I (XXX) wifi:phy: rx data from 00:11:22:33:44:55, len: 104, dat: 0, sn: 151, fn: 0, tid: 0, first_seq: 247
I (XXX) wifi:connected with YOUR_SSID, channel 1, BSSID 00:11:22:33:44:55
I (XXX) wifi:pm start, type: 0
I (XXX) DHCP_CLIENT: DHCP: Successfully obtained IPv4 address!
I (XXX) DHCP_CLIENT: IP: 192.168.1.100
I (XXX) DHCP_CLIENT: Netmask: 255.255.255.0
I (XXX) DHCP_CLIENT: Gateway: 192.168.1.1
I (XXX) DHCP_CLIENT: DNS Primary: 192.168.1.1
I (XXX) DHCP_CLIENT: DNS Secondary: 8.8.8.8

The XXX represents timestamps. The IP addresses and other network parameters will vary based on your network configuration. You might also see the DHCP: Lost IPv4 address! warning if the network connection is interrupted or the lease expires without renewal.

Variant Notes

The DHCP client functionality in ESP-IDF is implemented within the LwIP TCP/IP stack and managed by the esp_netif component. This design makes the DHCP client logic largely independent of the specific ESP32 variant being used.

All ESP32 variants (ESP32, ESP32-S2, ESP32-S3, ESP32-C3, ESP32-C6, ESP32-H2) support the Wi-Fi interface. Therefore, the DHCP client example provided in this chapter, which uses Wi-Fi, is fully applicable to all these variants without any code changes.

For scenarios involving wired Ethernet:

  • ESP32 (Classic): This variant has an internal Ethernet MAC and can directly connect to an external PHY. When using the Ethernet interface with esp_netif_create_default_eth(), the DHCP client will also be enabled by default and function identically to the Wi-Fi example.
  • ESP32-S2, ESP32-S3, ESP32-C3, ESP32-C6, ESP32-H2: These variants do not have an internal Ethernet MAC and require an external SPI/SDIO Ethernet controller (e.g., W5500). While the underlying driver initialization for these external controllers differs, once the esp_netif instance is created and attached to the Ethernet driver, the DHCP client behavior (handled by LwIP) remains the same.

In summary, the DHCP client implementation at the application layer using esp_netif and event handlers is consistent across all ESP32 variants. The primary difference might be in the initial setup of the specific network interface (Wi-Fi vs. different Ethernet hardware).

Common Mistakes & Troubleshooting Tips

Mistake / Issue Symptom(s) Troubleshooting / Solution
No DHCP Server on Network ESP32 fails to obtain an IP address. IP_EVENT_STA_GOT_IP (or IP_EVENT_ETH_GOT_IP) never triggers. Logs may show repeated connection attempts or DHCP timeouts.
  • Ensure the ESP32 is connected to a network with an active DHCP server (usually a router).
  • Test DHCP functionality on the same network with another device (e.g., laptop, phone).
  • Check router configuration to ensure DHCP server is enabled and has available IP addresses in its pool.
Incorrect Wi-Fi Credentials ESP32 fails to connect to the Wi-Fi AP. DHCP process doesn’t start. Logs show Wi-Fi connection failures (WIFI_EVENT_STA_DISCONNECTED with reason codes like WIFI_REASON_AUTH_FAIL).
  • Double-check Wi-Fi SSID and password in menuconfig or your code. They are case-sensitive.
  • Ensure the Wi-Fi network is in range and the ESP32 antenna is properly connected.
Physical Layer Connectivity Issues No IP address obtained. Underlying connection (Wi-Fi or Ethernet) is unstable or not established.
  • Wi-Fi: Check signal strength. Move ESP32 closer to AP. Check for interference.
  • Ethernet: Verify cable connections. Check link/activity LEDs on PHY and router. Ensure correct GPIOs for PHY are configured if using ESP32 classic.
Firewall Blocking DHCP Packets DHCP Discover messages from ESP32 might not reach the server, or Offer messages from server might not reach ESP32.
  • DHCP uses UDP ports 67 (server) and 68 (client).
  • Temporarily disable firewalls on router or intermediate devices for testing.
  • If resolved, configure firewall to allow DHCP traffic (UDP ports 67 & 68).
DHCP Server Pool Exhausted DHCP server has no more IP addresses to lease out. ESP32 will not receive an IP.
  • Check DHCP server (router) configuration for the IP address pool size and current leases.
  • Increase pool size or reduce lease times if many devices connect.
MAC Address Filtering on Router Router is configured to only allow specific MAC addresses to connect or obtain IPs. ESP32’s MAC address might not be on the allow list.
  • Check router’s MAC filtering/access control settings.
  • Add ESP32’s MAC address to the allow list or disable MAC filtering for testing. (ESP32 MAC can be found in logs or via API).
IP Address Conflicts (Rare with DHCP) ESP32 gets an IP, but experiences intermittent connectivity. Another device on the network might be using the same IP statically.
  • Check router’s DHCP lease table and connected devices list.
  • Ensure no static IPs are configured within the DHCP server’s dynamic pool.
  • Consider DHCP reservation for the ESP32’s MAC address on the router for a consistent IP.

Exercises

Exercise 1: Display DHCP Lease Information

Enhance the DHCP client example to retrieve and display the DHCP lease time. Additionally, implement a mechanism to periodically log the remaining lease time.

Steps:

  1. Include esp_netif_dhcp.h: This header provides functions to interact with the DHCP client state.
  2. Retrieve Lease Time: After IP_EVENT_STA_GOT_IP, use esp_netif_dhcpc_get_client_info() to get the DHCP client’s information, which includes the lease time.
  3. Periodic Logging Task: Create a FreeRTOS task that runs every few seconds (e.g., 5-10 seconds). Inside this task, retrieve the current time and the lease information, then calculate and log the remaining lease time.
  4. Test: Flash the code and observe the serial monitor. You should see the initial lease time and then periodic updates showing it counting down.

Exercise 2: DHCP Client State Monitoring

Implement a more detailed monitoring of the DHCP client’s internal state transitions. The esp_netif component allows querying the DHCP client’s current state.

Steps:

  1. Query DHCP State: In a separate FreeRTOS task, or periodically in your main loop, use esp_netif_dhcpc_get_state() to get the current state of the DHCP client (e.g., ESP_NETIF_DHCP_INIT, ESP_NETIF_DHCP_DISCOVERING, ESP_NETIF_DHCP_REQUESTING, ESP_NETIF_DHCP_BOUND, ESP_NETIF_DHCP_STOPPED).
  2. Log State Changes: Log the state whenever it changes. You might need to poll this function or use a custom event handler if the DHCP client exposes more granular state change events (check ESP-IDF documentation for advanced DHCP events).
  3. Simulate Disconnection: Temporarily disconnect the Wi-Fi or Ethernet cable to observe the DHCP client transitioning to a LOST_IP or DISCOVERING state.
  4. Test: Flash the code and observe the detailed DHCP state transitions in the serial monitor.

Exercise 3: Conditional Network Service Start

Modify the example so that a simple network service (e.g., a basic HTTP server, or a ping to a public IP) only starts after the IP_EVENT_STA_GOT_IP event is received, ensuring the ESP32 has a valid IP address. The service should stop if IP_EVENT_STA_LOST_IP occurs.

Steps:

  1. Define Service Task: Create a FreeRTOS task (e.g., network_service_task) that implements a simple network functionality (e.g., an HTTP server or a periodic ping to 8.8.8.8).
  2. Control Task Lifecycle:
    • In the event_handler for IP_EVENT_STA_GOT_IP, create and start the network_service_task. Store its task handle.
    • In the event_handler for IP_EVENT_STA_LOST_IP, check if the network_service_task is running. If so, signal it to stop (e.g., via a FreeRTOS event group or a flag) and then delete the task.
  3. Task Logic: The network_service_task should include a loop that performs its function and checks for a stop signal.
  4. Test: Flash the code. Observe the network service starting only after an IP is obtained. Then, temporarily disconnect the network (e.g., turn off Wi-Fi on the router) and observe the service stopping, and then restarting when the network is re-established.

Summary

  • DHCP (Dynamic Host Configuration Protocol) automates the assignment of IP addresses and other network configurations to devices.
  • The DHCP process follows the DORA sequence: Discover, Offer, Request, and Acknowledge.
  • IP addresses are assigned via a lease, which has a defined lease time and requires periodic renewal.
  • DHCP servers can provide various options, including subnet mask, default gateway, and DNS server addresses.
  • The ESP-IDF’s esp_netif component simplifies DHCP client implementation, automatically handling the DORA process when a default network interface is created (e.g., esp_netif_create_default_wifi_sta()).
  • Key events to monitor are IP_EVENT_STA_GOT_IP (IP obtained) and IP_EVENT_STA_LOST_IP (IP lost).
  • The DHCP client functionality is consistent across all ESP32 variants, as it relies on the LwIP stack and esp_netif abstraction, regardless of the underlying Wi-Fi or Ethernet hardware.
  • Common troubleshooting involves verifying DHCP server availability, correct network credentials, physical connectivity, and firewall settings.

Further Reading

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top