使用Java获取WiFi网络上的所有设备
我正在尝试查找设备所连接的WiFi网络上的所有设备。这是纯Java,不是Android。我需要搜索每个设备,看看它是否有一个特定的端口打开。我将通过使用Java获取WiFi网络上的所有设备,java,wifi,Java,Wifi,我正在尝试查找设备所连接的WiFi网络上的所有设备。这是纯Java,不是Android。我需要搜索每个设备,看看它是否有一个特定的端口打开。我将通过套接字连接到第一个符合此条件的设备,因此我需要它的IP地址。我实际上是在尝试编写以下代码: for (WiFiDevice device : WiFi.getConnectedDevices()) { if (device.hasPortOpen(1234)) { this.socket = new Socket(device
套接字连接到第一个符合此条件的设备,因此我需要它的IP地址。我实际上是在尝试编写以下代码:
for (WiFiDevice device : WiFi.getConnectedDevices()) {
if (device.hasPortOpen(1234)) {
this.socket = new Socket(device.getIPAddress(), 1234);
}
}
这个黑客解决方案怎么样:
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);
}
}
导入java.net.InetAddress;
导入java.net.Socket;
公共班机{
公共静态void main(字符串[]args){
int超时=500;
int端口=1234;
试一试{
字符串currentIP=InetAddress.getLocalHost().toString();
字符串subnet=getSubnet(当前IP);
System.out.println(“子网:+子网”);
对于(inti=1;i这是我的答案,它在我的Mac电脑上运行良好,但有点粗糙
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();
}
我不确定这是否可能,即使是从本机代码中。@immibis那将是一个耻辱。Android不能做到这一点,或者这是某种特殊的硬件/软件吗?我在Android上看到了:@RickS所有这些答案都直接与Android有关,但我想这表明它是可能的……我想这可以工作,但你认为ide可以吗我在上面提出的建议会更好?当然,使用arp是一个更好的主意。请记住,Runtime.getRuntime().exec(…)
是特定于平台的。如果您想要一个可移植的应用程序,最好使用“纯java”解决方案。