2014-07-19 193 views
0

我正在製作一個Android應用程序,用它的IP響應UDP廣播。這是代碼:與其DatagramPacket confirm = new DatagramPacket(send, send.length, listenSocket.getRemoteSocketAddress());迴應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.getInetAddress(), listenSocket.getPort()); 

getPort()給人-1(表示沒有連接套接字)和getInetAddress()給出了空,也表明它是不是連接的。

如何響應UDP廣播連接?

謝謝

回答

0

我有解決方案!

您必須從接收到的DatagramPacket中獲取IP地址和端口;

DatagramPacket confirm = new DatagramPacket(send, send.length, receivedPacket.getAddress(), receivedPacket.getPort());