sockets - 响应UDP广播

  显示原文与译文双语对照的内容
0 0

我正在制作一个 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 +"rn";
 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广播连接?

谢谢

时间:原作者:1个回答

0 0

我有解决方案 !

你必须从接收的DatagramPacket中获取IP地址和端口;

DatagramPacket confirm = new DatagramPacket(send, send.length, receivedPacket.getAddress(), receivedPacket.getPort());
原作者:
...