zoukankan      html  css  js  c++  java
  • 【转载】获取本机IP地址

    转载自:详谈再论JAVA获取本机IP地址

    // 正确的IP拿法
    System.out.println("get LocalHost LAN Address : " + getLocalHostLANAddress().getHostAddress());
    // 正确的IP拿法,即优先拿site-local地址
        private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
            try {
                InetAddress candidateAddress = null;
                // 遍历所有的网络接口
                for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
                    NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                    // 在所有的接口下再遍历IP
                    for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                        InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                        if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                            if (inetAddr.isSiteLocalAddress()) {
                                // 如果是site-local地址,就是它了
                                return inetAddr;
                            } else if (candidateAddress == null) {
                                // site-local类型的地址未被发现,先记录候选地址
                                candidateAddress = inetAddr;
                            }
                        }
                    }
                }
                if (candidateAddress != null) {
                    return candidateAddress;
                }
                // 如果没有发现 non-loopback地址.只能用最次选的方案
                InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
                if (jdkSuppliedAddress == null) {
                    throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
                }
                return jdkSuppliedAddress;
            } catch (Exception e) {
                UnknownHostException unknownHostException = new UnknownHostException(
                        "Failed to determine LAN address: " + e);
                unknownHostException.initCause(e);
                throw unknownHostException;
            }
        }
  • 相关阅读:
    mongodb的安装与启动(centos7)
    使用tengine解决负载均衡的session问题
    nginx 负载均衡 使用ip_hash方式解决session问题 测试
    查看linux服务器状态常用命令
    swagger
    使用gtest(googletest)进行c++单元测试
    程序员的字符艺术
    使用gdb调试c++程序
    使用c++开发跨平台的程序
    Orleans之EventSourcing
  • 原文地址:https://www.cnblogs.com/LinQingYang/p/12848977.html
Copyright © 2011-2022 走看看