Home / References / ESP32 Library / AsyncUDP Library
Description
The localPort() method is used to retrieve the local port number where a UDP packet was received. This method is part of the AsyncUDPPacket class and returns the destination port number that was used when the packet was sent to the ESP32. It’s particularly useful for applications that listen on multiple ports simultaneously, for implementing port-based routing and filtering, debugging network communications to verify correct port targeting, implementing protocol multiplexing where different services use different ports, and creating flexible server applications that can handle requests on various ports. The method provides essential information for understanding the network communication flow and implementing port-aware packet processing logic.
This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
Syntax and Usage
The localPort() method has a simple syntax and is called on an AsyncUDPPacket object:
Get local port number:
uint16_t localPortNum = packet.localPort()Returns the local port number where the packet was received.
Arguments
The localPort() method takes no arguments.
For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
Return Value
The localPort() method returns a uint16_t (16-bit unsigned integer) containing the local port number where the UDP packet was received. This value represents the destination port that was specified when the packet was sent to the ESP32. The port number is automatically extracted from the UDP header and converted from network byte order to host byte order. Valid port numbers range from 0 to 65535, with ports 0-1023 typically reserved for system services, and ports 1024-65535 available for user applications.
For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
Example Code
Multi-Port UDP Monitor with Port Analysis
This example demonstrates how to use localPort() in an advanced scenario with multiple listening ports and detailed port-based packet analysis. It provides comprehensive packet monitoring with port-specific statistics and routing capabilities.
How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. The ESP32 will listen for UDP packets on multiple ports (8001, 8002, 8888) and display detailed information about each received packet, including which port received it. This is particularly useful for debugging network issues, implementing port-based services, and understanding packet routing in multi-port applications.
/*
* 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 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- ESP32 AsyncUDP Librarry
- Connection Management
- Data Transimission
- Broadcast Multicast
- Network Information
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
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!