I have an application that requires sending and receiving of UDP messages. The flow is:
Local system sends out a UDP broadcast from a randomly assigned local port (e.g. 50001) to systems listening on a predefined port number (e.g. 6000).
Remote system listening on 6000 (there will only ever be one that replies) reads the message and checks the address and port, and replies back with a UDP unicast message on the same port that was used to send the message (50001 in this case).
The application works for earlier Android version, but it doesn't for 8.1 or 9. Would anyone know why?
I've written a very basic bit of code to illustrate the problem. This code works (i.e. I can send out a broadcast and read the return UDP messages) when the local system is Windows, or an Android emulator running versions 4.4, 6, or 7 of Android. It breaks when I run the emulator with version 8.1, or using a real device with version 9. In the later cases, the UDP broadcast goes out, the remote system reads and replies on the correct port (verified with Wireshark) but the UDP message is never read by the Android system.
In all cases, the remote system is a separate physical device on my local network.
void runUDP()
{
UdpClient udpClient = new UdpClient();
try
{
// Need to send and receive from the same port
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.EnableBroadcast = true;
// Bind to a port
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, 0));
// Broadcast dummy message to systems listening on port 6000
udpClient.Send(new byte[] { 1, 2, 3, 4 }, 4, new IPEndPoint(IPAddress.Parse("192.168.3.255"),6000));
//Prepare to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host. The remote host replies on the same port
// that the local host used for broadcasting
byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}