ESP32 AsyncUDP Library – listenIP()

Home / References / ESP32 Library / AsyncUDP Library

Description

The listenIP() method is used to retrieve the remote IP address that the AsyncUDP object is currently connected to or listening for. This method is part of the AsyncUDP class and returns the IP address of the remote endpoint when the UDP socket is in a connected state. It’s particularly useful for UDP client applications that have established a connection to a specific remote server, for debugging and logging network connections, verifying connection targets in client-server communications, and implementing connection-aware UDP protocols. The method automatically handles both IPv4 and IPv6 addresses when IPv6 support is enabled, making it versatile for modern network applications. Note that this method returns the remote IP address stored in the UDP Protocol Control Block (PCB), which is set when using connect() or listenMulticast() methods.

Syntax and Usage

The listenIP() method has a simple syntax and is called on an AsyncUDP object:

Get remote IP address:  

IPAddress remoteAddr = udp.listenIP()

Returns the remote IP address that the UDP socket is connected to or configured for.

Arguments

The listenIP() method takes no arguments.

Return Value

The listenIP() method returns an IPAddress object containing the remote IP address stored in the UDP Protocol Control Block. For IPv4 connections, it returns the standard IPv4 address. For IPv6-enabled builds, it returns an empty IPAddress object if the connection is IPv6 (use listenIPv6() for IPv6 addresses). If the UDP socket is not connected or no remote IP is set, it returns an empty or invalid IPAddress object. This method is most useful after calling connect() or listenMulticast() methods.

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

Example Code

UDP Client with Connection Monitoring

This example demonstrates how to use the listenIP() method to monitor the remote IP address in a UDP client application. The client connects to a remote UDP server and periodically displays the connection information, making it useful for understanding UDP connection state and debugging network connectivity.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials and server details. The ESP32 will connect to the specified UDP server and periodically send messages while displaying the remote IP address. The Serial Monitor will show the connection status and remote IP information, helping you verify the UDP connection.

/*
 * Author: Avant Maker
 * Date: January 15, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use the listenIP() method to monitor
 * the remote IP address in a UDP client application. The client connects
 * to a remote UDP server and periodically displays the connection information,
 * making it useful for understanding UDP connection state and debugging
 * network connectivity.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials and
 * server details. The ESP32 will connect to the specified UDP server
 * and periodically send messages while displaying the remote IP address.
 * The Serial Monitor will show the connection status and remote IP
 * information, helping you verify the UDP connection.
 *
 * Test setup: You can use netcat on a computer as a UDP server:
 * nc -u -l 8080
 * Or set up any UDP server on your network.
 *
 * 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

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

AsyncUDP udp;
unsigned long lastSend = 0;
unsigned long lastStatus = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP32 AsyncUDP listenIP() Client 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("Local IP address: ");
  Serial.println(WiFi.localIP());
  
  // Connect to remote UDP server
  IPAddress serverIP;
  if (serverIP.fromString(remoteHost)) {
    if (udp.connect(serverIP, remotePort)) {
      Serial.println("UDP connection established!");
      
      // Display connection information
      IPAddress listenAddr = udp.listenIP();
      Serial.print("Connected to remote IP: ");
      Serial.println(listenAddr.toString());
      Serial.print("Remote port: ");
      Serial.println(remotePort);
      
      // Set up packet handler for responses
      udp.onPacket([](AsyncUDPPacket packet) {
        Serial.println("=== Response Received ===");
        
        String message = "";
        for (int i = 0; i < packet.length(); i++) {
          message += (char)packet.data()[i];
        }
        
        Serial.print("From: ");
        Serial.print(packet.remoteIP().toString());
        Serial.print(":");
        Serial.println(packet.remotePort());
        Serial.print("Message: ");
        Serial.println(message);
        Serial.print("Size: ");
        Serial.print(packet.length());
        Serial.println(" bytes");
        Serial.println("========================");
      });
      
    } else {
      Serial.println("Failed to connect to UDP server");
    }
  } else {
    Serial.println("Invalid server IP address");
  }
}

void loop() {
  // Send periodic messages to server
  if (millis() - lastSend > 5000) { // Every 5 seconds
    lastSend = millis();
    
    if (udp.connected()) {
      String message = "Hello from ESP32 at " + String(millis()) + "ms";
      udp.print(message);
      Serial.println("Sent: " + message);
    } else {
      Serial.println("UDP not connected");
    }
  }
  
  // Display periodic connection status
  if (millis() - lastStatus > 15000) { // Every 15 seconds
    lastStatus = millis();
    
    Serial.println("=== Connection Status ===");
    Serial.print("Connected: ");
    Serial.println(udp.connected() ? "Yes" : "No");
    
    IPAddress listenAddr = udp.listenIP();
    Serial.print("Remote IP (listenIP): ");
    if (listenAddr.toString() != "0.0.0.0") {
      Serial.println(listenAddr.toString());
    } else {
      Serial.println("Not set");
    }
    
    Serial.print("Free heap: ");
    Serial.print(ESP.getFreeHeap());
    Serial.println(" bytes");
    Serial.println("========================");
  }
  
      delay(100);
  }

UDP Server Code for Testing

This server code is designed to work with the client example above. Upload this code to a separate ESP32 dev board to create a test server that the client can connect to and communicate with. The server listens for incoming UDP packets and responds with acknowledgments, making it perfect for testing the listenIP() functionality.

How to use this server code: Upload this code to a second ESP32 dev board and replace the WiFi credentials. Make sure both ESP32 boards are connected to the same WiFi network. Note the server’s IP address from the Serial Monitor and update the client code’s remoteHost variable to match the server’s IP address. The server will listen on port 8080 and respond to any incoming UDP packets, allowing you to test the client’s listenIP() method functionality.

/*
 * Author: Avant Maker
 * Date: January 15, 2025
 * Version: 1.0
 * License: MIT
 * 
 * Description: 
 * UDP Server for testing the ESP32 AsyncUDP listenIP() client examples.
 * This server listens for incoming UDP packets on port 8080 and responds
 * with acknowledgments. It's designed to work with the client examples
 * in the listenIP() documentation, providing a complete testing setup
 * for UDP communication between two ESP32 devices.
 *
 * How to use this server code:
 * 1. Upload this code to a second ESP32 dev board
 * 2. Replace the WiFi credentials below
 * 3. Make sure both ESP32 boards are on the same WiFi network
 * 4. Note the server's IP address from Serial Monitor
 * 5. Update the client code's remoteHost variable to match this IP
 * 6. The server will automatically respond to client packets
 *
 * Features:
 * - Listens on port 8080 for UDP packets
 * - Displays detailed information about received packets
 * - Sends acknowledgment responses to clients
 * - Shows connection statistics and client information
 * - Monitors multiple clients simultaneously
 *
 * 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;
unsigned long packetCount = 0;
unsigned long lastStats = 0;

// Structure to track client information
struct ClientInfo {
  IPAddress ip;
  uint16_t port;
  unsigned long lastSeen;
  unsigned long packetCount;
  String lastMessage;
};

ClientInfo clients[10]; // Support up to 10 clients
int clientCount = 0;

// Function to find or add client
int findClient(IPAddress ip, uint16_t port) {
  // First, try to find existing client
  for (int i = 0; i < clientCount; i++) {
    if (clients[i].ip == ip && clients[i].port == port) {
      return i;
    }
  }
  
  // If not found and we have space, add new client
  if (clientCount < 10) {
    clients[clientCount].ip = ip;
    clients[clientCount].port = port;
    clients[clientCount].packetCount = 0;
    return clientCount++;
  }
  
  return -1; // No space for new clients
}

void setup() {
  Serial.begin(115200);
  Serial.println("ESP32 AsyncUDP Server - listenIP() Test Server");
  
  // 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("Server IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Update your client code to use this IP address");
  Serial.println("===============================================");
  
  // Start UDP server on port 8080
  if (udp.listen(8080)) {
    Serial.println("UDP Server started on port 8080");
    Serial.println("Waiting for client connections...");
    
    // Set up packet handler
    udp.onPacket([](AsyncUDPPacket packet) {
      packetCount++;
      
      // Get packet information
      IPAddress clientIP = packet.remoteIP();
      uint16_t clientPort = packet.remotePort();
      IPAddress localIP = packet.localIP();
      uint16_t localPort = packet.localPort();
      
      // Extract message
      String message = "";
      for (int i = 0; i < packet.length(); i++) {
        message += (char)packet.data()[i];
      }
      
      // Find or add client
      int clientIndex = findClient(clientIP, clientPort);
      if (clientIndex >= 0) {
        clients[clientIndex].lastSeen = millis();
        clients[clientIndex].packetCount++;
        clients[clientIndex].lastMessage = message;
      }
      
      // Display packet information
      Serial.println("=== UDP Packet Received ===");
      Serial.printf("Packet #%lu\n", packetCount);
      Serial.printf("From Client: %s:%d\n", clientIP.toString().c_str(), clientPort);
      Serial.printf("To Server: %s:%d\n", localIP.toString().c_str(), localPort);
      Serial.printf("Message: %s\n", message.c_str());
      Serial.printf("Size: %d bytes\n", packet.length());
      Serial.printf("Packet Type: %s\n", packet.isBroadcast() ? "Broadcast" : 
                    packet.isMulticast() ? "Multicast" : "Unicast");
      
      if (clientIndex >= 0) {
        Serial.printf("Client Packets: %lu\n", clients[clientIndex].packetCount);
      }
      
      // Send acknowledgment response
      String response = "ACK: Server received '" + message + "' at " + String(millis()) + "ms";
      packet.printf("%s", response.c_str());
      
      Serial.printf("Sent Response: %s\n", response.c_str());
      Serial.println("============================");
    });
    
  } else {
    Serial.println("Failed to start UDP server");
  }
}

void loop() {
  // Display periodic server statistics
  if (millis() - lastStats > 30000) { // Every 30 seconds
    lastStats = millis();
    
    Serial.println("=== Server Statistics ===");
    Serial.printf("Server IP: %s\n", WiFi.localIP().toString().c_str());
    Serial.printf("Total packets received: %lu\n", packetCount);
    Serial.printf("Active clients: %d\n", clientCount);
    Serial.printf("Free heap: %d bytes\n", ESP.getFreeHeap());
    Serial.printf("WiFi Signal: %d dBm\n", WiFi.RSSI());
    Serial.printf("Uptime: %lu seconds\n", millis() / 1000);
    
    // Display client information
    if (clientCount > 0) {
      Serial.println("--- Connected Clients ---");
      unsigned long currentTime = millis();
      for (int i = 0; i < clientCount; i++) {
        unsigned long timeSinceLastSeen = (currentTime - clients[i].lastSeen) / 1000;
        Serial.printf("Client %d: %s:%d\n", i + 1, 
                      clients[i].ip.toString().c_str(), clients[i].port);
        Serial.printf("  Packets: %lu, Last seen: %lu sec ago\n", 
                      clients[i].packetCount, timeSinceLastSeen);
        Serial.printf("  Last message: %s\n", clients[i].lastMessage.c_str());
      }
    }
    Serial.println("========================");
  }
  
  delay(100);
}

Complete Testing Setup Instructions

To create a complete testing environment for the listenIP() method, follow these steps:

  1. Prepare two ESP32 dev boards: You’ll need one for the client code and one for the server code.
  2. Upload server code: Upload the server code above to the first ESP32 dev board. This will be your UDP server.
  3. Note server IP: After the server connects to WiFi, note its IP address from the Serial Monitor (e.g., “192.168.1.150”).
  4. Update client code: In the client code, change the remoteHost variable to match your server’s IP address.
  5. Upload client code: Upload the modified client code to the second ESP32 dev board.
  6. Test communication: Both boards should now communicate via UDP. The client will use listenIP() to display the server’s IP address, and the server will respond to all client messages.
  7. Monitor both Serial outputs: Open Serial Monitors for both boards to see the complete communication flow and verify the listenIP() functionality.

Expected behavior: The client will connect to the server and periodically send messages. The client’s Serial Monitor will show the remote IP address obtained via listenIP(), while the server’s Serial Monitor will display detailed information about received packets and send acknowledgment responses back to the client.

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

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 !!