我正在尝试发现我的设备所连接的WiFi网络上的所有设备。这是普通的Java,而不是Android。我需要搜索每个设备,看看它是否有特定的端口打开。我将通过Socket
连接到我发现的第一个符合此条件的设备,因此我需要其IP地址。我基本上试图编写以下代码:
for (WiFiDevice device : WiFi.getConnectedDevices()) {
if (device.hasPortOpen(1234)) {
this.socket = new Socket(device.getIPAddress(), 1234);
}
}
答案 0 :(得分:1)
这个hacky解决方案怎么样:
import java.net.InetAddress;
import java.net.Socket;
public class Main {
public static void main(String[] args) {
int timeout=500;
int port = 1234;
try {
String currentIP = InetAddress.getLocalHost().toString();
String subnet = getSubnet(currentIP);
System.out.println("subnet: " + subnet);
for (int i=1;i<254;i++){
String host = subnet + i;
System.out.println("Checking :" + host);
if (InetAddress.getByName(host).isReachable(timeout)){
System.out.println(host + " is reachable");
try {
Socket connected = new Socket(subnet, port);
}
catch (Exception s) {
System.out.println(s);
}
}
}
}
catch(Exception e){
System.out.println(e);
}
}
public static String getSubnet(String currentIP) {
int firstSeparator = currentIP.lastIndexOf("/");
int lastSeparator = currentIP.lastIndexOf(".");
return currentIP.substring(firstSeparator+1, lastSeparator+1);
}
}
答案 1 :(得分:0)
这是我的回答,它在我的Mac上运行良好,但有点hacky。
Socket socket = new Socket();
try {
Process process = Runtime.getRuntime().exec("arp -i en0 -a -n");
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (reader.ready()) {
String ip = reader.readLine();
ip = ip.substring(3, ip.indexOf(')'));
try {
socket.connect(new InetSocketAddress(ip, 1234), 1000);
System.out.println("Found socket!");
} catch (ConnectException | SocketTimeoutException ignored) {
}
}
if (socket == null) {
System.err.println("Could not find socket.");
}
} catch (Exception e) {
e.printStackTrace();
}