微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

根据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地址.为什么?我的本地网络中有设备,如高级IP扫描仪扫描中所示.

解决方法

尝试增加超时.我用了大约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
    }
}

为我工作完美.

原文地址:https://www.jb51.cc/java/129263.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐