可显示本地 IP,例如 192.168.0.1

public static InetAddress getLocalHostLANAddress() throws Exception {
    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();
        return jdkSuppliedAddress;
    } catch (Exception e) {e.printStackTrace();
    }
    return null;
} 
           
           
           
