为什么Java获取主机名的缓存版本?

时间:2016-04-17 19:59:51

标签: java

请参考这个问题:

https://askubuntu.com/questions/758432/is-there-another-place-to-host-machine-name?noredirect=1#comment1132454_758432

如您所见,我使用此方法获取计算机名称:

private InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = en.nextElement();
        for (Enumeration<InetAddress> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
} 

来电者:

InetAddress ip = getFirstNonLoopbackAddress(true, false);
this.machineName = ip.getCanonicalHostName();

但结果是我在Ubuntu中更改它之前得到旧机器名。

如何在/ etc / hostname文件中获取真实的机器/主机名?

1 个答案:

答案 0 :(得分:2)

dns总是缓存名称。你应该在你正在使用的操作系统中执行刷新dns;在Ubuntu上我找到了关于如何刷新dns的信息:

https://askubuntu.com/questions/414826/how-to-flush-dns-in-ubuntu-12-04

或尝试这种方法: Flush DNS using Java