Home / References / ESP32 Library / AsyncUDP Library
Description
The length() method is a fundamental function of the AsyncUDPPacket class that returns the size of the received UDP packet data in bytes. This method is essential for determining how much data was received in a UDP packet, enabling developers to properly process and parse the packet contents. The length() method works in conjunction with the data() method to provide complete access to received packet information – while data() provides a pointer to the packet content, length() tells you exactly how many bytes are available to read. This is crucial for safe memory operations and proper data processing in UDP communication.
Syntax and Usage
The length() method can be used in the following way:
Basic Usage: size_t packetSize = packet.length();
– Retrieves the size of the received packet data in bytes
// Example of basic usage
void onPacketReceived(AsyncUDPPacket packet) {
size_t dataLength = packet.length();
// Use the length to safely process packet data
}This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
Argument(s)
This method does not require any arguments.
Return Value
The length() method returns a value of type size_t that represents the total number of bytes contained in the received UDP packet’s payload. This value indicates the exact amount of data available for reading from the packet. The returned length corresponds to the number of bytes that can be safely accessed using the data() method pointer. A return value of 0 indicates an empty packet, while larger values represent the actual size of the received data payload.
Example Codes
Example 1: UDP Server (Receiver) – Testing length() Method
This example demonstrates how to create a UDP server that receives packets and uses the length() method to determine packet sizes and process the received data safely.
/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use the length() method to determine
* the size of incoming UDP packets and safely process received data
* based on packet length information. This is the SERVER/RECEIVER code.
*
* How to use this example (Server Setup):
* 1. Upload this code to your ESP32 (Server)
* 2. Connect the ESP32 to your WiFi network
* 3. Note the IP address displayed in Serial Monitor
* 4. Use the companion UDP Client code below to send test data
* 5. Monitor the Serial output to see length() method in action
*
* Testing with the companion client:
* - Run this server code first
* - Then run the UDP Client Sender code (Example 2 below) on another device
* - The client will automatically send various packet sizes
* - Observe how the length() method reports different packet sizes
*
* 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
#include
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
AsyncUDP udp;
void setup() {
Serial.begin(115200);
// 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...");
udp.onPacket([](AsyncUDPPacket packet) {
// Get packet length using length() method
size_t packetLength = packet.length();
uint8_t* packetData = packet.data();
Serial.print("Received packet with length: ");
Serial.print(packetLength);
Serial.println(" bytes");
// Process data based on packet length
if (packetLength == 0) {
Serial.println("Empty packet received");
} else if (packetLength <= 10) {
Serial.println("Small packet (≤10 bytes):");
for (size_t i = 0; i < packetLength; i++) {
Serial.print("0x");
Serial.print(packetData[i], HEX);
Serial.print(" ");
}
Serial.println();
} else if (packetLength <= 50) {
Serial.println("Medium packet (11-50 bytes):");
// Display as string if printable
Serial.print("As string: ");
for (size_t i = 0; i < packetLength; i++) {
if (packetData[i] >= 32 && packetData[i] <= 126) {
Serial.print((char)packetData[i]);
} else {
Serial.print(".");
}
}
Serial.println();
} else {
Serial.print("Large packet (");
Serial.print(packetLength);
Serial.println(" bytes):");
Serial.println("First 20 bytes:");
for (size_t i = 0; i < min(packetLength, (size_t)20); i++) {
Serial.print("0x");
Serial.print(packetData[i], HEX);
Serial.print(" ");
}
Serial.println();
}
Serial.print("From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.println(packet.remotePort());
Serial.println("---");
});
} else {
Serial.println("Failed to start UDP server!");
}
}
void loop() {
// Main loop - UDP handling is done asynchronously
delay(1000);
}Example 2: UDP Client (Sender) – Testing Companion Code
This companion example demonstrates how to send UDP packets of various sizes to test the length() method functionality on the receiving ESP32. It acts as a UDP client that sends different packet sizes to help demonstrate the length() method capabilities. This is the CLIENT/SENDER code.
/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.1 (Fixed)
* License: MIT
*
* Description:
* This companion example demonstrates how to send UDP packets of various
* sizes to test the length() method functionality on the receiving ESP32.
* It acts as a UDP client that sends different packet sizes to help
* demonstrate the length() method capabilities. This is the CLIENT/SENDER code.
*
* FIXED VERSION - Corrected UDP sending issues
*
* How to use this example (Client Setup):
* 1. First, upload and run Example 1 (UDP Server) on your ESP32 server
* 2. Note the IP address displayed by the server in Serial Monitor
* 3. Update the SERVER_IP constant below with the server's IP address
* 4. Upload this code to another ESP32 or compatible device (Client)
* 5. Open Serial Monitor on both devices to see packet transmission
* 6. Observe the server's Serial Monitor to see length() method processing
*
* Complete testing procedure:
* - Run the UDP Server (Example 1) first and note its IP address
* - Update SERVER_IP in this client code with the server's IP
* - Run this client code on a second device
* - The client will automatically send packets of different sizes every 5 seconds
* - Watch both Serial Monitors to see the complete packet size transmission and processing
*
* 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
#include
// WiFi credentials
const char* ssid = "your_SSID"; // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password
// Server configuration (update with your server ESP32's IP address)
const char* SERVER_IP = "192.168.0.123"; // Change this to your server's IP
const int SERVER_PORT = 1234;
AsyncUDP udp;
IPAddress serverIP;
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 5000; // Send every 5 seconds
int messageCounter = 0;
void setup() {
Serial.begin(115200);
Serial.println("UDP Client Sender Starting...");
// Convert server IP string to IPAddress object
serverIP.fromString(SERVER_IP);
// 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("Client IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Will send data to server: ");
Serial.print(SERVER_IP);
Serial.print(":");
Serial.println(SERVER_PORT);
Serial.println("UDP client ready to send packets of various sizes!");
Serial.println("---");
}
void loop() {
// Send different sized packets every 5 seconds
if (millis() - lastSendTime >= sendInterval) {
sendVariousSizedPackets();
lastSendTime = millis();
messageCounter++;
}
delay(100);
}
void sendVariousSizedPackets() {
Serial.print("Sending test packets (Round ");
Serial.print(messageCounter + 1);
Serial.println("):");
// 1. Send empty packet (0 bytes)
Serial.println("1. Sending empty packet (0 bytes)");
size_t bytesSent = udp.writeTo(nullptr, 0, serverIP, SERVER_PORT);
Serial.print(" Bytes sent: ");
Serial.println(bytesSent);
delay(500);
// 2. Send tiny packet (5 bytes)
Serial.println("2. Sending tiny packet (5 bytes)");
uint8_t tinyData[] = {0x01, 0x02, 0x03, 0x04, 0x05};
bytesSent = udp.writeTo(tinyData, sizeof(tinyData), serverIP, SERVER_PORT);
Serial.print(" Bytes sent: ");
Serial.println(bytesSent);
delay(500);
// 3. Send small packet (15 bytes)
Serial.println("3. Sending small packet (15 bytes)");
String smallMessage = "Hello ESP32!";
bytesSent = udp.writeTo((uint8_t*)smallMessage.c_str(), smallMessage.length(), serverIP, SERVER_PORT);
Serial.print(" Bytes sent: ");
Serial.println(bytesSent);
delay(500);
// 4. Send medium packet (35 bytes)
Serial.println("4. Sending medium packet (35 bytes)");
String mediumMessage = "This is a medium-sized UDP packet";
bytesSent = udp.writeTo((uint8_t*)mediumMessage.c_str(), mediumMessage.length(), serverIP, SERVER_PORT);
Serial.print(" Bytes sent: ");
Serial.println(bytesSent);
delay(500);
// 5. Send large packet (100 bytes)
Serial.println("5. Sending large packet (100 bytes)");
uint8_t largeData[100];
for (int i = 0; i < 100; i++) {
largeData[i] = i % 256; // Fill with sequential values
}
bytesSent = udp.writeTo(largeData, sizeof(largeData), serverIP, SERVER_PORT);
Serial.print(" Bytes sent: ");
Serial.println(bytesSent);
delay(500);
// 6. Send JSON packet (variable size)
Serial.println("6. Sending JSON packet");
String jsonData = "{\"round\":" + String(messageCounter + 1) + ",\"sensor\":\"temperature\",\"value\":25.4,\"unit\":\"celsius\",\"timestamp\":" + String(millis()) + "}";
bytesSent = udp.writeTo((uint8_t*)jsonData.c_str(), jsonData.length(), serverIP, SERVER_PORT);
Serial.print(" JSON packet size: ");
Serial.print(jsonData.length());
Serial.print(" bytes, Bytes sent: ");
Serial.println(bytesSent);
Serial.println("--- All test packets sent ---");
Serial.println();
}How to Use Both Examples Together
To fully test the length() method functionality, follow these steps:
- Set up the Server: Upload Example 1 (UDP Server) to your first ESP32 and note its IP address from the Serial Monitor
- Configure the Client: In Example 2 (UDP Client), update the
SERVER_IPconstant with your server’s IP address - Deploy the Client: Upload Example 2 to a second ESP32 or compatible device
- Observe the Testing: The client will automatically send packets of various sizes every 5 seconds:
- Empty packets (0 bytes) to test edge cases
- Tiny packets (5 bytes) with binary data
- Small packets (15 bytes) with text messages
- Medium packets (35 bytes) with longer text
- Large packets (100 bytes) with sequential data
- Variable-sized JSON packets for real-world scenarios
- Monitor Results: Watch both Serial Monitors to see how the
length()method accurately reports different packet sizes, and observe how the server processes packets differently based on their length
This comprehensive testing setup demonstrates the importance and versatility of the length() method in UDP packet processing, showing how packet size information is crucial for safe data handling, memory management, and implementing size-based processing logic in ESP32 UDP communication applications.
For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
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!