我需要从设备发送请求,该请求在当前网络(wifi)上查找已经实现了客户端的特定设备。我需要获取所有此类设备的IP地址。到目前为止,我有这个:
protected Void doInBackground(Void... voids) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(7432);
byte[] msg = new byte[]{0,2,9,0,4};
Log.d("sending", "Sending data " + Arrays.toString(msg));
DatagramPacket packet = new DatagramPacket(msg, msg.length,
InetAddress.getByName("192.168.1.255"), 7432);
socket.send(packet);
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
while (true) {
if (socket != null){
socket.receive(packet);
}
String s = String.valueOf(packet.getAddress());
Log.e("response", "Received response " + s);
}
} catch (SocketTimeoutException e) {
Log.d("timeout", "Receive timed out");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
我也尝试使用255.255.255.255
,但出现此错误:
E/adbd: failed to connect to socket 'localabstract:com.example.fixxxer.skyzapper': Connection refused
我什至不确定目前为止的代码是否正确,但是令人惊讶的是,网上没有足够的信息,因此一旦我尝试也无法正常工作。我在这个问题上停留了很长时间。