Home / References / ESP32 Library / AsyncUDP Library
Description
The remoteIP() method is used to retrieve the remote IP address of the sender of a UDP packet. This method is part of the AsyncUDPPacket class and returns the IP address of the device that sent the UDP packet. It’s particularly useful for identifying packet sources in network applications, implementing client-server communication patterns, creating UDP-based communication protocols, and building network monitoring and logging systems. The method automatically handles both IPv4 and IPv6 addresses when IPv6 support is enabled, providing seamless compatibility across different network configurations. This makes it an essential tool for any UDP-based application that needs to track or respond to packet senders.
This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
Syntax and Usage
The remoteIP() method has a simple syntax and is called on an AsyncUDPPacket object:
Get remote IP address:
IPAddress remoteAddr = packet.remoteIP()Returns the IP address of the device that sent the UDP packet.
Arguments
The remoteIP() method takes no arguments.
Return Value
The remoteIP() method returns an IPAddress object containing the remote IP address of the device that sent the UDP packet. For IPv4 addresses, it returns the standard IPv4 address of the sender. For IPv6-enabled builds, it returns an empty IPAddress object if the packet was sent from an IPv6 address (use remoteIPv6() for IPv6 addresses). If the packet information is not available or corrupted, it returns an empty or invalid IPAddress object.
Example Code
Advanced Example: UDP Packet Source Tracker
This example demonstrates how to use the remoteIP() method in an advanced UDP monitoring application that tracks packet sources and provides detailed sender analysis. The application listens for UDP packets and maintains comprehensive statistics about each sender, including packet counts, timing information, and network interface details.
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 sender, including their IP address, packet statistics, and communication patterns. This is particularly useful for network analysis, security monitoring, and understanding traffic patterns in UDP-based applications.
/*
* Author: Avant Maker
* Date: January 15, 2025
* Version: 1.0
* License: MIT
*
* Description:
* Advanced UDP Packet Source Tracker that demonstrates remoteIP() usage
* with comprehensive sender analysis and statistics. This example provides
* detailed monitoring of UDP packet sources, tracking sender information,
* packet counts, timing data, and communication patterns. It's particularly
* useful for network analysis, security monitoring, debugging UDP applications,
* and understanding traffic patterns in complex network environments.
*
* 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 sender, including their IP address, packet statistics,
* and communication patterns. This is particularly useful for network analysis,
* security monitoring, and understanding traffic patterns in UDP-based applications.
*
* Test with netcat: echo "Test message" | nc -u ESP32_IP_ADDRESS 8888
* Or use any UDP client to send packets to port 8888.
*
* Features:
* - Comprehensive sender tracking and statistics
* - Packet source identification and analysis
* - Communication pattern detection
* - Network security monitoring capabilities
* - Real-time sender information display
* - Memory and performance monitoring
*
* 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>
#include <map>
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";
AsyncUDP udp;
unsigned long totalPackets = 0;
// Structure to track sender statistics
struct SenderStats {
unsigned long packetCount;
unsigned long firstSeen;
unsigned long lastSeen;
unsigned long totalBytes;
String lastMessage;
uint16_t lastPort;
};
// Map to store sender statistics
std::map<String, SenderStats> senderMap;
void setup() {
Serial.begin(115200);
Serial.println("ESP32 UDP Packet Source Tracker");
// 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());
Serial.println("Starting UDP Packet Source Tracker on port 8888");
// Start UDP listener on port 8888
if (udp.listen(8888)) {
Serial.println("UDP Source Tracker listening on port 8888");
Serial.println("Send UDP packets to analyze source information");
udp.onPacket([](AsyncUDPPacket packet) {
totalPackets++;
// Get sender information using remoteIP()
IPAddress senderIP = packet.remoteIP();
uint16_t senderPort = packet.remotePort();
IPAddress localIP = packet.localIP();
uint16_t localPort = packet.localPort();
// Convert sender IP to string for mapping
String senderKey = senderIP.toString();
// Get packet data
String message = "";
size_t packetSize = packet.length();
for (size_t i = 0; i < packetSize && i < 200; i++) { // Limit to first 200 chars
char c = packet.data()[i];
message += (c >= 32 && c <= 126) ? c : '.'; // Show printable chars only
}
// Update sender statistics
unsigned long currentTime = millis();
if (senderMap.find(senderKey) == senderMap.end()) {
// New sender
SenderStats newSender;
newSender.packetCount = 1;
newSender.firstSeen = currentTime;
newSender.lastSeen = currentTime;
newSender.totalBytes = packetSize;
newSender.lastMessage = message;
newSender.lastPort = senderPort;
senderMap[senderKey] = newSender;
Serial.printf("NEW SENDER DETECTED: %s\n", senderKey.c_str());
} else {
// Existing sender
senderMap[senderKey].packetCount++;
senderMap[senderKey].lastSeen = currentTime;
senderMap[senderKey].totalBytes += packetSize;
senderMap[senderKey].lastMessage = message;
senderMap[senderKey].lastPort = senderPort;
}
// Display detailed packet information
Serial.printf("Packet #%lu from %s:\n", totalPackets, senderKey.c_str());
Serial.printf(" Sender: %s:%d\n", senderIP.toString().c_str(), senderPort);
Serial.printf(" Receiver: %s:%d\n", localIP.toString().c_str(), localPort);
Serial.printf(" Size: %d bytes\n", packetSize);
Serial.printf(" Type: %s\n", packet.isBroadcast() ? "Broadcast" :
packet.isMulticast() ? "Multicast" : "Unicast");
Serial.printf(" Message: %s%s\n", message.c_str(), packetSize > 200 ? "..." : "");
// Display sender statistics
SenderStats stats = senderMap[senderKey];
Serial.printf(" Sender Stats:\n");
Serial.printf(" Total packets: %lu\n", stats.packetCount);
Serial.printf(" Total bytes: %lu\n", stats.totalBytes);
Serial.printf(" First seen: %lu ms ago\n", currentTime - stats.firstSeen);
Serial.printf(" Last seen: %lu ms ago\n", currentTime - stats.lastSeen);
Serial.printf(" Communication duration: %lu ms\n", stats.lastSeen - stats.firstSeen);
// Check for suspicious activity
if (stats.packetCount > 100) {
Serial.println(" WARNING: High packet count from this sender!");
}
if (stats.totalBytes > 10000) {
Serial.println(" WARNING: High data volume from this sender!");
}
Serial.println(" ---");
// Send acknowledgment back to sender
String ackMessage = "ACK from " + WiFi.localIP().toString() +
" - Packet #" + String(stats.packetCount) +
" received at " + String(currentTime) + "ms";
packet.printf("ACK: %s", ackMessage.c_str());
});
} else {
Serial.println("Failed to start UDP listener");
}
}
void loop() {
// Display periodic statistics
static unsigned long lastStats = 0;
if (millis() - lastStats > 30000) { // Every 30 seconds
lastStats = millis();
Serial.println("=== SENDER STATISTICS SUMMARY ===");
Serial.printf("Total packets received: %lu\n", totalPackets);
Serial.printf("Unique senders: %d\n", senderMap.size());
Serial.printf("Free heap: %d bytes\n", ESP.getFreeHeap());
Serial.printf("WiFi Signal: %d dBm\n", WiFi.RSSI());
// Display top senders
if (!senderMap.empty()) {
Serial.println("Top Senders by Packet Count:");
for (auto& sender : senderMap) {
Serial.printf(" %s: %lu packets, %lu bytes\n",
sender.first.c_str(),
sender.second.packetCount,
sender.second.totalBytes);
}
}
Serial.println("================================");
}
// Send periodic test packet to demonstrate functionality
static unsigned long lastTest = 0;
if (millis() - lastTest > 60000) { // Every minute
lastTest = millis();
// Send test packet to ourselves
String testMsg = "Self-test packet from " + WiFi.localIP().toString();
udp.writeTo((uint8_t*)testMsg.c_str(), testMsg.length(), WiFi.localIP(), 8888);
Serial.println("Sent self-test packet for demonstration");
}
delay(1000);
}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!