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

Bul*_*aza 8 java networking network-scan

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

根据这个答案,我按以下方式构建了我的代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不会打印出任何结果,这意味着无法访问任何IP地址.为什么?我的本地网络中有设备,如Advanced IP Scanner扫描中所见.

小智 6

尝试增加超时。我使用了大约 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
    }
}
Run Code Online (Sandbox Code Playgroud)

非常适合我。


小智 3

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 一台主机?