简体   繁体   中英

Respond to UDP broadcast

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM