查找本地网络中的所有IP地址
我想找到我当前使用Java代码连接到的本地网络中设备的所有IP地址。 有用的实用程序Advanced IP Scanner
能够在我的子网 192.168.178/24
找到各种IP地址:
根据这个答案,我按以下方式构建了我的代码:
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
扫描中所示。
InetAddress.isReachable将使用ICMP ECHO REQUEST(当您执行ping操作时)或请求端口7(echo端口): http : //docs.oracle.com/javase/7/docs/api/java/net/InetAddress。 HTML#isReachable%28int 29%
高级IP扫描程序可能使用其他方式来发现主机(例如radmin端口上的请求或http上的请求)。
主机可以启动但无法应答ICMP ECHO REQUEST。
您是否尝试从命令行ping其中一个主机?
尝试增加超时。 我用了大约5000毫秒,这对我很有帮助。 如果您不想等待5000ms * 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 } }
为我工作完美。
也许尝试使用InetAddress.getByAddress(host)
而不是getByName
,如下所示:
InetAddress localhost = InetAddress.getLocalHost(); byte[] ip = localhost.getAddress(); for (int i = 1; i <= 254; i++) { try { ip[3] = (byte)i; InetAddress address = InetAddress.getByAddress(ip); if (address.isReachable(100)) { output = address.toString().substring(1); System.out.print(output + " is on the network"); } }
我从这里拿了这个样本用于自动检测代码
Java 8流解决方案
IntStream.rangeClosed(1,254).mapToObj(num -> "192.168.0."+num).parallel() .filter((addr) -> { try { return InetAddress.getByName(addr).isReachable(2000); } catch (IOException e) { return false; } } ).forEach(System.out::println);