UDP broadcast between endpoints

Hello,
I want to connect a bunch of ESP32 via WIFI using UDP in my home, they should be able to listen to a master sender (my phone) and receive commands from it. They should also be able to occasionally send data from one ESP32 to all others. I am following a simple example:

#include "WiFi.h"
#include "AsyncUDP.h"

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

AsyncUDP udp;

void setup() {

  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed");
    while (1) {
      delay(1000);
    }
  }
  if (udp.listenMulticast(IPAddress(239,255,43,21), 45454)) {
    Serial.print("UDP Listening on IP: ");
    Serial.println(WiFi.localIP());
    udp.onPacket([](AsyncUDPPacket packet) {
      Serial.print("UDP Packet Type: ");
      Serial.print(packet.isBroadcast() ? "Broadcast" : packet.isMulticast() ? "Multicast" : "Unicast");
      Serial.print(", From: ");
      Serial.print(packet.remoteIP());
      Serial.print(":");
      Serial.print(packet.remotePort());
      Serial.print(", To: ");
      Serial.print(packet.localIP());
      Serial.print(":");
      Serial.print(packet.localPort());
      Serial.print(", Length: ");
      Serial.print(packet.length());
      Serial.print(", Data: ");
      Serial.write(packet.data(), packet.length());
      Serial.println();
      //reply to the client
      packet.printf("Got %u bytes of data", packet.length());
    });
    //Send multicast
    udp.print("Hello!");
  }
}

void loop() {
  delay(1000);
  //Send multicast
  udp.print("Anyone here?");
}

This all works as expected but when the 2nd ESP32 enters the same network it is flooding it with this message:

"UDP Packet Type: Unicast, From: 192.168.0.27:45454, To: 192.168.0.35:45454, Length: 20, Data: Got 20 bytes of data"

The "Anyone here" message does come thru every second as well:

"UDP Packet Type: Multicast, From: 192.168.0.35:45454, To: 239.255.43.21:45454, Length: 12, Data: Anyone here?"

My question is: how can I disable the avalanche of Unicast messages?

Thanks,
Markus

Have you tried another port, like 5005?

1 Like

not sure why that should make a difference but I tried it with the same results

The issue you are facing with the ESP32 network setup is that when an ESP32 receives a multicast packet, it replies with a Unicast message back to the sender

When multiple devices are on the same network, this creates an avalanche of Unicast messages.

➜ Just avoid responding to multicast messages with a Unicast reply

1 Like

brilliant! that was it, thanks :slightly_smiling_face:

glad it helped :slight_smile:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.