Reputation: 1798
I am making an Android app that responds to a UDP broadcast with its IP. This is the code:
byte[] buf = new byte[128];
final DatagramPacket packet = new DatagramPacket(buf, buf.length);
listenSocket.receive(packet);
Toast.makeText(network, "UDP connection detected.", Toast.LENGTH_LONG).show();
if (packet.getData()[0] == 0x1 && packet.getData()[1] == 0x42) { //respond to broadcast:
String ip = Utils.getIP() + ":" + COMM_PORT + "\r\n";
final byte[] send = new byte[32];
send[0] = 0x1;
send[1] = 0x43;
System.arraycopy(ip.getBytes(), 0, send, 2, 20);
Toast.makeText(network, Arrays.toString(send), Toast.LENGTH_LONG).show();
Toast.makeText(network, "IP address is null?" + (listenSocket.getInetAddress() == null), Toast.LENGTH_LONG).show(); // this prints IP address is null?true to the console
DatagramPacket confirm = new DatagramPacket(send, send.length, listenSocket.getRemoteSocketAddress()); //FAILS HERE
listenSocket.send(confirm);
listenSocket.close();
}
Instead of DatagramPacket confirm = new DatagramPacket(send, send.length, listenSocket.getRemoteSocketAddress());
I have tried:
DatagramPacket confirm = new DatagramPacket(send, send.length, listenSocket.getInetAddress(), listenSocket.getPort());
but getPort()
gives -1 (indicating socket is not connected) and getInetAddress() gives null, also indicating it is not connected.
How do I respond to a UDP broadcast connection?
Thanks
Upvotes: 0
Views: 703
Reputation: 1798
I have the solution!
You have to get the IP address and port from the received DatagramPacket;
DatagramPacket confirm = new DatagramPacket(send, send.length, receivedPacket.getAddress(), receivedPacket.getPort());
Upvotes: 2