Question

In my Android app I'm sending a UDP broadcast to address 255.255.255.255, port 6400. I use the PC program Packet Sender to act as a UDP server that automatically sends a reply.

When I'm listening for this reply in the Android app, it never receives the reply. I can only receive the reply if I don't send the packet to 255.255.255.255, but to the specific IP address of the PC.

private String udpDestinationAddress = "255.255.255.255";
private int udpDestinationPort = 6400;
private int udpTimeoutMs = 5000;
private String udpData = "test";

DatagramSocket socket;
socket = new DatagramSocket(12345);
socket.setBroadcast(true);
socket.setSoTimeout(udpTimeoutMs);
socket.connect(InetAddress.getByName(udpDestinationAddress), udpDestinationPort);

// send part
byte[] data = udpData.getBytes();
int length = data.length;
DatagramPacket packet = new DatagramPacket(data, length);               
socket.send(packet);

// receive part
byte[] buffer = new byte[1000];

// Initialize the packet
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

// Receive the packet
socket.receive(packet); // it timeouts here (if timeout=0, then it hangs here forever)

// Get the host IP
String hostIP = packet.getAddress().toString().replace("/", "");

In the PC program, I have set it to reply automatically (with another random string) to a packet on port 6400. This works quite well with other apps I've tested (various UDP test Android apps). However, my app cannot seem to get the reply.

I can only get a reply in my app when I've set udpDestinationAddress to the specific IP of the PC. I've also tried "192.168.5.255" (broadcast on my local subnet) instead of "255.255.255.255" - still doesn't work.

Was it helpful?

Solution

I found the problem.

Instead of binding the destination IP and port to the socket, I needed to bind it to the packet instead.

So, instead of:

socket.connect(InetAddress.getByName(udpDestinationAddress), udpDestinationPort);
...
DatagramPacket packet = new DatagramPacket(data, length);

... use this instead:

InetAddress addr = InetAddress.getByName("255.255.255.255");
DatagramPacket packet = new DatagramPacket(udpData.getBytes(), udpData.length(), addr, udpDestinationPort);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top