Chat freely about anything...

User avatar
By Maurice
#60957 I wrote some Android UDP code to send a UDP packet on port 4045.

I receive that packet on the ESP8266 and check UDPWifi.remotePort() and it says some other port number and this port number changes with each packet I receive. If I try to reply to the host with 4045 it is never received, but I need to use that remotePort() value.

Can someone explain why this is happening?

Android Code:
Code: Select all            DatagramPacket packet = new DatagramPacket(data, packSize, mAddress, mIpPort);
            mSocket.send(packet);

            packet = new DatagramPacket(data, data.length, mAddress, mIpPort);
            mSocket.receive(packet);


ESP8266 Arduino Code:
Code: Select allvoid loop() {
  int udpSize = gUDP.parsePacket();
  int serialSize = Serial.available();
  static uint8 gPacketSize = 0;
  static IPAddress gIp;
  char buf[256];

  if (udpSize > 0) {
    gIp = gUDP.remoteIP();
    gPort = gUDP.remotePort();
    udpSize = gUDP.readBytes(buf, 256);
    Serial.write(buf, udpSize);
  }

  if (serialSize > 0) {
   
    if (gPacketSize == 0) {
      Serial.readBytes(&gPacketSize, 1);
    }

    if (serialSize >= gPacketSize-1) {
      buf[0] = gPacketSize;
      Serial.readBytes(buf+1, gPacketSize-1);
      gUDP.beginPacket(gIp, gPort);
      gUDP.write(buf, gPacketSize);
      gUDP.endPacket();
      gPacketSize = 0;
      Serial.println(gPort);
    }
  }
}
User avatar
By Maurice
#61014 I tracked down the problem and wanted to post back here in case others hit the issue.

The problem was I wasn't specifying a port in the Android code when creating a socket. I changed my socket generation code to the following and things behaved as expected.

mSocket = new DatagramSocket(mIpPort);