ESP32 AsyncUDP Library – localIP()

Home / References / ESP32 Library / AsyncUDP Library

Description

The localIP() method is used to retrieve the local IP address of the device that received a UDP packet. This method is part of the AsyncUDPPacket class and returns the IP address of the network interface where the packet was received. It’s particularly useful for multi-homed devices (devices with multiple network interfaces) to determine which interface received the packet, for logging and debugging UDP communications, implementing network diagnostics, and handling packets differently based on the receiving interface. The method automatically handles both IPv4 and IPv6 addresses when IPv6 support is enabled, making it versatile for modern network applications.

This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.

Syntax and Usage

The localIP() method has a simple syntax and is called on an AsyncUDPPacket object:

IPAddress localAddr = packet.localIP()

Returns the local IP address where the packet was received.

Arguments

The localIP() method takes no arguments.

Return Value

The localIP() method returns an IPAddress object containing the local IP address of the network interface that received the UDP packet. For IPv4 addresses, it returns the standard IPv4 address. For IPv6-enabled builds, it returns an empty IPAddress object if the packet was received on an IPv6 interface (use localIPv6() for IPv6 addresses). If the packet information is not available, it returns an empty or invalid IPAddress object.

For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on  AvantMaker.com

Example Code

Simple UDP Server with Local IP Display

This example demonstrates how to use the localIP() method to display the local IP address when UDP packets are received. The server listens on port 1234 and shows which interface received each packet, making it useful for understanding network routing and multi-interface scenarios.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. After connecting, the ESP32 will listen for UDP packets on port 1234. You can send test packets using tools like netcat or any UDP client. The Serial Monitor will display the local IP address where each packet was received, along with the sender’s information and packet content.

/*
 * Author: Avant Maker
 * Date: January 15, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use the localIP() method to display
 * the local IP address when UDP packets are received. The server listens
 * on port 1234 and shows which interface received each packet, making it
 * useful for understanding network routing and multi-interface scenarios.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials.
 * After connecting, the ESP32 will listen for UDP packets on port 1234.
 * You can send test packets using tools like netcat or any UDP client.
 * The Serial Monitor will display the local IP address where each packet
 * was received, along with the sender's information and packet content.
 *
 * Test with netcat: echo "Hello ESP32" | nc -u ESP32_IP_ADDRESS 1234
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <AsyncUDP.h>

const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

AsyncUDP udp;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP32 AsyncUDP localIP() Example");
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  // Start UDP server on port 1234
  if (udp.listen(1234)) {
    Serial.println("UDP server started on port 1234");
    Serial.println("Waiting for UDP packets...");
    
    // Set up packet handler
    udp.onPacket([](AsyncUDPPacket packet) {
      // Get local IP address where packet was received
      IPAddress localAddr = packet.localIP();
      
      // Get remote IP address and port
      IPAddress remoteAddr = packet.remoteIP();
      uint16_t remotePort = packet.remotePort();
      
      // Get packet data
      String message = "";
      for (int i = 0; i < packet.length(); i++) {
        message += (char)packet.data()[i];
      }
      
      // Display packet information
      Serial.println("=== UDP Packet Received ===");
      Serial.print("Local IP (where received): ");
      Serial.println(localAddr.toString());
      Serial.print("From: ");
      Serial.print(remoteAddr.toString());
      Serial.print(":");
      Serial.println(remotePort);
      Serial.print("Message: ");
      Serial.println(message);
      Serial.print("Packet size: ");
      Serial.print(packet.length());
      Serial.println(" bytes");
      
      // Check if packet was broadcast or multicast
      if (packet.isBroadcast()) {
        Serial.println("Packet Type: Broadcast");
      } else if (packet.isMulticast()) {
        Serial.println("Packet Type: Multicast");
      } else {
        Serial.println("Packet Type: Unicast");
      }
      
      Serial.println("===========================");
      
      // Send a response back to the sender
      String response = "Received on " + localAddr.toString() + " at " + String(millis()) + "ms";
      packet.printf("ACK: %s", response.c_str());
    });
  } else {
    Serial.println("Failed to start UDP server");
  }
}

void loop() {
  // Send a test packet every 30 seconds to demonstrate the functionality
  static unsigned long lastSend = 0;
  if (millis() - lastSend > 30000) {
    lastSend = millis();
    
    // Send a test packet to ourselves (loopback test)
    udp.writeTo((uint8_t*)"Self-test packet", 16, WiFi.localIP(), 1234);
    Serial.println("Sent self-test packet");
  }
  
  delay(100);
}

Advanced Example: Multi-Interface UDP Monitor

This example shows how to use localIP() in a more advanced scenario with multiple network interfaces and detailed packet analysis. It provides comprehensive packet monitoring with statistics and interface identification.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. The ESP32 will listen for UDP packets on port 8888 and display detailed information about each received packet, including which network interface received it. This is particularly useful for debugging network issues and understanding packet routing in complex network environments.

/*
 * Author: Avant Maker
 * Date: January 15, 2025
 * Version: 1.0
 * License: MIT
 * 
 * Description: 
 * Advanced Multi-Interface UDP Monitor that demonstrates localIP() usage
 * with detailed network interface analysis. This example provides comprehensive
 * packet monitoring capabilities, showing detailed information about each
 * received UDP packet including source/destination IPs, packet types, and
 * network interface identification. It's particularly useful for debugging
 * network routing issues and understanding multi-homed device behavior.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials.
 * The ESP32 will listen for UDP packets on port 8888 and display detailed
 * information about each received packet, including which network interface
 * received it. This is particularly useful for debugging network issues and
 * understanding packet routing in complex network environments.
 *
 * Test with netcat: echo "Test packet" | nc -u ESP32_IP_ADDRESS 8888
 * Or use any UDP client to send packets to port 8888.
 *
 * Features:
 * - Packet counting and statistics
 * - Interface identification
 * - Packet type detection (Unicast/Broadcast/Multicast)
 * - Memory and WiFi signal monitoring
 * - Printable character filtering for packet data display
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <AsyncUDP.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

AsyncUDP udp;
unsigned long packetCount = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP32 Multi-Interface UDP Monitor");
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("Station IP: ");
  Serial.println(WiFi.localIP());
  
  // Start UDP listener on port 8888
  if (udp.listen(8888)) {
    Serial.println("UDP Monitor listening on port 8888");
    
    udp.onPacket([](AsyncUDPPacket packet) {
      packetCount++;
      
      // Get all IP information
      IPAddress localIP = packet.localIP();
      IPAddress remoteIP = packet.remoteIP();
      uint16_t localPort = packet.localPort();
      uint16_t remotePort = packet.remotePort();
      
      // Create packet summary
      String data = "";
      size_t len = packet.length();
      for (size_t i = 0; i < len && i < 100; i++) { // Limit to first 100 chars
        char c = packet.data()[i];
        data += (c >= 32 && c <= 126) ? c : '.'; // Show printable chars only
      }
      
      // Display detailed packet information
      Serial.printf("Packet #%lu:\n", packetCount);
      Serial.printf("  Local IP: %s:%d\n", localIP.toString().c_str(), localPort);
      Serial.printf("  Remote IP: %s:%d\n", remoteIP.toString().c_str(), remotePort);
      Serial.printf("  Size: %d bytes\n", len);
      Serial.printf("  Type: %s\n", packet.isBroadcast() ? "Broadcast" : 
                    packet.isMulticast() ? "Multicast" : "Unicast");
      Serial.printf("  Data: %s%s\n", data.c_str(), len > 100 ? "..." : "");
      
      // Check if received on expected interface
      if (localIP == WiFi.localIP()) {
        Serial.println("  Interface: WiFi Station");
      } else {
        Serial.println("  Interface: Other/Unknown");
      }
      
      Serial.println("  ---");
    });
  }
}

void loop() {
  // Display periodic statistics
  static unsigned long lastStats = 0;
  if (millis() - lastStats > 60000) { // Every minute
    lastStats = millis();
    Serial.printf("Statistics: %lu packets received\n", packetCount);
    Serial.printf("Free heap: %d bytes\n", ESP.getFreeHeap());
    Serial.printf("WiFi Signal: %d dBm\n", WiFi.RSSI());
  }
  
  delay(1000);
}

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!

error: Content is protected !!