Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 544
imrichardcole Avatar asked Oct 22 '15 20:10

imrichardcole


People also ask

What is InetAddress getLocalHost ()?

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.

Can InetAddress be used with I need 6?

An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.

What InetAddress means?

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.

What is InetAddress getByName?

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.


2 Answers

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)

like image 90
imrichardcole Avatar answered Oct 14 '22 16:10

imrichardcole


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.

like image 41
Octavian R. Avatar answered Oct 14 '22 16:10

Octavian R.