Java獲取機(jī)器IP

現(xiàn)象:在進(jìn)行數(shù)據(jù)測試時(shí),無意發(fā)現(xiàn)某臺(tái)機(jī)器返回的IP不正確,其返回的為127.0.0.1。但其它機(jī)器均為正常。

該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.

通過跟蹤源碼發(fā)現(xiàn),是因?yàn)闆]有設(shè)置主機(jī)的hostname導(dǎo)致的。其解析的邏輯是根據(jù)localHostName來獲取的,而localHostName在虛擬機(jī)里面默認(rèn)為localhost.localdomain,而localhost.localdomain對(duì)應(yīng)的則默認(rèn)為127.0.0.1,
更改機(jī)器的hostname即可
,其更改hostname方法如下:

hostnamectl set-hostname xxx

可以通過以下獲取所有的IP(針對(duì)多網(wǎng)卡),并且對(duì)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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容