獲取本機ip

public 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;
}

https://www.cnblogs.com/xiaoBlog2016/p/7076230.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章