美文网首页
Java获取机器IP

Java获取机器IP

作者: 三无架构师 | 来源:发表于2017-09-05 12:39 被阅读117次

    现象:在进行数据测试时,无意发现某台机器返回的IP不正确,其返回的为127.0.0.1。但其它机器均为正常。

    该IP是通过InetAddress.getLocalHost()获取IP地址,查看该方法见其注释为:

     * <p>If there is a security manager, its
     * {@code checkConnect} method is called
     * with the local host name and {@code -1}
     * as its arguments to see if the operation is allowed.
     * If the operation is not allowed, an InetAddress representing
     * the loopback address is returned.
    

    通过跟踪源码发现,是因为没有设置主机的hostname导致的。其解析的逻辑是根据localHostName来获取的,而localHostName在虚拟机里面默认为localhost.localdomain,而localhost.localdomain对应的则默认为127.0.0.1,
    更改机器的hostname即可
    ,其更改hostname方法如下:

    hostnamectl set-hostname xxx
    

    可以通过以下获取所有的IP(针对多网卡),并且对IP6地址过滤:

    public static List<String> getHostAddresses(Boolean filterIp6) {
        List<String> result = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> address = networkInterface.getInetAddresses();
                while (address.hasMoreElements()) {
                    InetAddress add = address.nextElement();
                    if (filterIp6 == null || filterIp6.booleanValue() == true) {
                        if (add.getHostAddress().contains(":")) {
                            continue;
                        }
                    }
                    result.add(add.getHostAddress());
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return result;
    }
    

    相关文章

      网友评论

          本文标题:Java获取机器IP

          本文链接:https://www.haomeiwen.com/subject/kxyujxtx.html