我需要使用android设备在wifi网络中“查找”特定设备。设备正在端口7432
上侦听,我需要以字节为单位发送02904
并获得IP地址响应。设备数量可能从0
到n。我需要每个设备上的IP地址(来自响应或发现)
到目前为止,这是我的代码(我并不是说它对我有用):
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DiscoveryThread implements Runnable {
@Override
public void run() {
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
DatagramSocket socket = new DatagramSocket(7432, InetAddress.getByName("255.255.255.255"));
socket.setBroadcast(true);
do {
System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!");
//Receive a packet
byte[] recvBuf = new byte[5];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet);
//Packet received
System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData()));
//See if the packet holds the right command (message)
String message = new String(packet.getData()).trim();
if (message.equals("DISCOVER_FUIFSERVER_REQUEST")) {
byte[] sendData = "DISCOVER_FUIFSERVER_RESPONSE".getBytes();
//Send a response
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
socket.send(sendPacket);
System.out.println(getClass().getName() + ">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
}
} while (true);
} catch (IOException ex) {
Logger.getLogger(DiscoveryThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
static DiscoveryThread getInstance() {
return DiscoveryThreadHolder.INSTANCE;
}
private static class DiscoveryThreadHolder {
private static final DiscoveryThread INSTANCE = new DiscoveryThread();
}
}
我尝试过:
Android send udp broadcast silently fails
https://lab.dyne.org/AndroidUDPBroadcast
http://rocknirmana.blogspot.com/2013/08/sending-udp-broadcast-socket-messages.html
https://jackiexie.com/2015/07/15/network-discovery-using-udp-broadcast-java/
https://developer.android.com/reference/java/net/DatagramSocket
http://www.helloandroid.com/tutorials/simple-udp-communication-example
https://www.baeldung.com/java-broadcast-multicast
https://answers.unity.com/questions/250732/android-build-is-not-receiving-udp-broadcasts.html
https://pzoleeblogen.wordpress.com/2014/03/04/android-udp-broadcast-message-is-not-received/
清单:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
在我链接的大多数示例中,我得到的响应是“ 192.168.0.230”,并且我需要一个IP列表,例如["192.168.0.101", "192.168.0.102", "192.168.0.103"]
(这是它们在我的网络上的外观,我看到了它们在具有这些IP的路由器中,我只是无法在我的应用中获取它们)。
我对网络不太熟悉,也许我是用错误的方式开始的,但是我变得绝望了。