gpt4 book ai didi

java - 查找本地网络中的所有IP地址

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:49:59 25 4
gpt4 key购买 nike

我想使用 Java 代码查找当前连接到的本地网络中设备的所有 IP 地址。有用的实用程序 Advanced IP Scanner能够在我的 subnet 中找到各种 IP 地址192.168.178/24:

根据 this回答,我按照以下方式构建了我的代码:

import java.io.IOException;
import java.net.InetAddress;

public class IPScanner
{
public static void checkHosts(String subnet) throws IOException
{
int timeout = 100;
for (int i = 1; i < 255; i++)
{
String host = subnet + "." + i;
if (InetAddress.getByName(host).isReachable(timeout))
{
System.out.println(host + " is reachable");
}
}
}

public static void main(String[] arguments) throws IOException
{
checkHosts("192.168.178");
}
}

不幸的是,这不会打印出任何结果,这意味着无法访问任何 IP 地址。为什么?我的本地网络中有一些设备,如在 Advanced IP Scanner 扫描中看到的那样。

最佳答案

尝试增加超时。我用了大约 5000 毫秒,这对我有帮助。如果您不想等待 5000 毫秒 * 254 = 21 分钟,也可以尝试使用此代码并行 ping 地址:

public static void getNetworkIPs() {
final byte[] ip;
try {
ip = InetAddress.getLocalHost().getAddress();
} catch (Exception e) {
return; // exit method, otherwise "ip might not have been initialized"
}

for(int i=1;i<=254;i++) {
final int j = i; // i as non-final variable cannot be referenced from inner class
new Thread(new Runnable() { // new thread for parallel execution
public void run() {
try {
ip[3] = (byte)j;
InetAddress address = InetAddress.getByAddress(ip);
String output = address.toString().substring(1);
if (address.isReachable(5000)) {
System.out.println(output + " is on the network");
} else {
System.out.println("Not Reachable: "+output);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start(); // dont forget to start the thread
}
}

非常适合我。

关于java - 查找本地网络中的所有IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32500182/

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