InetAddress.getLocalHost() slow to run (30+ seconds)

后端 未结 5 2094
独厮守ぢ
独厮守ぢ 2020-11-28 06:19

With the following code:

try {
  System.out.println(new Date());
  InetAddress hostName = InetAddress.getLocalHost();
  System.out.println(new Date());
} cat         


        
相关标签:
5条回答
  • 2020-11-28 06:24

    The above answer works on my mac, you can try it like this:

    step 1, download inetTester.jar from enter link description here

    step 2, run it on your mac. here is the result on my mac:

    $ java -jar ./inetTester.jar
    Calling the hostname resolution method...
    Method called, hostname MacBook-Pro.local, elapsed time: 5009 (ms)
    

    it takes 5s to run the test, and it shows the hostname of my mac.

    step 3, modify the /etc/hosts:

    127.0.0.1   MacBook-Pro.local
    ::1         MacBook-Pro.local
    

    the host is what shows in step 2. and after this, run the test again:

    $ java -jar ./inetTester.jar
    Calling the hostname resolution method...
    Method called, hostname MacBook-Pro.local, elapsed time: 6 (ms)
    

    yeah, it comes with only 6ms. 5s -> 6ms, nice.

    0 讨论(0)
  • 2020-11-28 06:25

    This problem appears on MacOS Sierra using Java8, updates equals or bigger than 60 (jdk1.8.0_60.jdk, jdk1.8.0_77.jdk, etc).

    The solution can be found here: https://github.com/thoeni/inetTester.

    This is the content of my /etc/hosts file:

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

    In my case, mac is my computer name.

    0 讨论(0)
  • 2020-11-28 06:34

    I suspect the delay here was due to a failed attempt at DNS resolution. Perhaps your DNS servers were not configured correctly. The 30 seconds probably represents the timeout on the DNS resolution.

    The reason your solution improved the speed is that adding the entry to the hosts file allowed the hostname to be resolved locally and thus skip the attempt to resolve the hostname against an actual (remote) DNS server.

    EDIT: You may wonder why this method does any host resolution at all. Apparently, it is part of an anti-spoofing mechanism built in to the Java networking library. See the accepted answer of this post for more details: InetAddress.getCanonicalHostName() returns IP instead of Hostname

    0 讨论(0)
  • 2020-11-28 06:42

    The issue can be solved by adding the following to /etc/hosts (assuming output of hostname command is my-macbook:

    127.0.0.1   my-macbook
    ::1         my-macbook
    

    This returns the time to something more suitable (< 1 second)

    0 讨论(0)
  • 2020-11-28 06:42

    On a MacBook Pro with Java 1.8.0_92 and 1.80_112 this problem is still existing, the call to InetAddress.getLocalhost() needs > 5 seconds. The solution with the modified /etc/hosts does not work. Only switching back to Java 1.8.0_051 solves this problem.

    0 讨论(0)
提交回复
热议问题