【问题标题】:How to discover Ip Addresses where listening on port x如何发现监听端口 x 的 IP 地址
【发布时间】:2012-09-26 00:28:54
【问题描述】:

我想从我的子网扫描 IP 范围。 我想保存将在特定端口上听到的 IP 地址。我使用此代码:

        for (int host = 1; host < 255; host++) {
            String ip = networkAddress + host;

            Socket socket;
            try {
                socket = new Socket(ip, port);
                System.out.println(ip + "  +");
                serverList.add(ip);
                socket.close();
            }
            catch (Exception e) {
                System.out.println(ip + "  -");
            }
        }

但我的问题是它需要太多时间...... 有没有更快的方法?

【问题讨论】:

    标签: java sockets local-network port-scanning


    【解决方案1】:

    使用多线程。由于大部分时间实际上都花在等待响应上,因此您可以安全地创建 100 个(甚至 200 个)线程,从而将总时间减少两个数量级。使用Executors 类创建线程池并为每个主机提交一个任务。

    请记住,serverList 集合必须是线程安全的。使用shutdown() 和awaitTermination() 对等待结果。或者使用CompletionService 在结果到达时收集结果。

    【讨论】:

      【解决方案2】:

      使用new Socket()(无参数),然后调用Socket.connect() 并设置一个较短的超时时间,比如几秒钟。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 2014-06-10
        • 1970-01-01
        相关资源
        最近更新 更多