InetAddress.getLocalHost() 运行缓慢 (30+ 秒)

2022-08-31 12:12:58

使用以下代码:

try {
  System.out.println(new Date());
  InetAddress hostName = InetAddress.getLocalHost();
  System.out.println(new Date());
} catch (UnknownHostException e) {
  e.printStackTrace();
}

我得到这个输出:

Thu Oct 22 20:58:22 BST 2015
Thu Oct 22 20:58:52 BST 2015

换句话说,执行时间为30秒。机器是2015年Macbook Pro与Java 1.8.0_60。

为什么这需要这么长时间?


答案 1

可以通过添加以下内容来解决该问题(假设命令的输出为:/etc/hostshostnamemy-macbook

127.0.0.1   my-macbook
::1         my-macbook

这会将时间返回到更合适的位置(< 1 秒)


答案 2

此问题出现在使用Java8的MacOS Sierra上,更新等于或大于60(jdk1.8.0_60.jdk,jdk1.8.0_77.jdk等)。

解决方案可以在这里找到:https://github.com/thoeni/inetTester

这是我的 /etc/hosts 文件的内容:

127.0.0.1   localhost mac.local
::1         localhost mac.local

在我的情况下,mac是我的计算机名称。


推荐