我想使用 Java 代码查找当前连接到的本地网络中设备的所有 IP 地址。有用的实用程序Advanced IP Scanner http://www.advanced-ip-scanner.com/能够在我的中找到各种IP地址subnet https://en.wikipedia.org/wiki/Subnetwork of 192.168.178/24
:
根据this https://stackoverflow.com/a/3345981/3764804回答,我按照以下方式构建了我的代码:
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
scan.
尝试增加超时时间。我用了大约 5000ms,这对我有帮助。
如果您不想等待 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
}
}
非常适合我。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)