gpt4 book ai didi

java - 使用 Java 获取 WiFi 网络上的所有设备

转载 作者:行者123 更新时间:2023-11-30 11:08:21 25 4
gpt4 key购买 nike

我正在尝试发现我的设备连接到的 WiFi 网络上的所有设备。这是纯 Java,不是 Android。我需要搜索每个设备以查看它是否打开了特定端口。我将通过 Socket 连接到我发现的第一台符合此条件的设备,因此我需要它的 IP 地址。我实际上是在尝试编写以下代码:

for (WiFiDevice device : WiFi.getConnectedDevices()) {
if (device.hasPortOpen(1234)) {
this.socket = new Socket(device.getIPAddress(), 1234);
}
}

最佳答案

这个 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);
}
}

关于java - 使用 Java 获取 WiFi 网络上的所有设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com