With the following code:
try { System.out.println(new Date()); InetAddress hostName = InetAddress.getLocalHost(); System.out.println(new Date()); } catch (UnknownHostException e) { e.printStackTrace(); }
I get this output:
Thu Oct 22 20:58:22 BST 2015 Thu Oct 22 20:58:52 BST 2015
In other words 30 seconds to execute. Machine is 2015 Macbook Pro with Java 1.8.0_60.
Why does this take so long?
Java InetAddress getLocalHost() method The getLocalHost() method of Java InetAddress class returns the instance of InetAddress containing local host name and address. In this, firstly the host name is retrieved from the system, then that name is resolved into InetAddress.
An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.
InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com, etc. An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name.
The getByName() method of InetAddress class determines the IP address of a host from the given host's name. If the host name is null, then an InetAddress representing an address of the loopback interface is returned.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With