我正在创建一个Android应用程序,用它的IP响应UDP广播。这是代码:
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();
}
而不是DatagramPacket confirm = new DatagramPacket(send, send.length, listenSocket.getRemoteSocketAddress());
我尝试过:
DatagramPacket confirm = new DatagramPacket(send, send.length, listenSocket.getInetAddress(), listenSocket.getPort());
但getPort()
给出-1(表示套接字未连接),getInetAddress()给出null,也表示它没有连接。
如何响应UDP广播连接?
由于
答案 0 :(得分:0)
我有解决方案!
您必须从收到的DatagramPacket获取IP地址和端口;
DatagramPacket confirm = new DatagramPacket(send, send.length, receivedPacket.getAddress(), receivedPacket.getPort());