Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java InetAddress.getHostName() taking a very long time to execute

I have the following little code snippet:

        InetAddress address = InetAddress.getByName(host);
        if(address.isReachable(TIMEOUT_IN_MILLISECONDS)) {
          System.out.println(host + " is reachable.");
          String hostName = address.getHostName();
          System.out.println(hostName);
        }

The getHostName() method is taking quite some time to execute if a machine has been found. Could someone please explain why?

like image 821
czchlong Avatar asked May 02 '12 19:05

czchlong


People also ask

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 is use of InetAddress getByName () function?

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.

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.


2 Answers

From the InetAddress#getHostName() javadocs, that method will perform a reverse hostname lookup. So the performance of that method call depends on the performance of the network/technology stack between the JVM and the domain name server for the target host.

In brief, that method will make a system call to perform the reverse lookup (e.g. getaddrinfo(3)) and that call will be implemented by the operating system to perform the network actions required to gather the host information via the Name Server configured for your machine.

like image 135
maerics Avatar answered Oct 04 '22 03:10

maerics


Some of the addresses need longer time to be resolved. InetAddress has a cache to store successful and unsuccessful resolutions. Also, make a threadpool. You can improve the performance

like image 22
Sunil Avatar answered Oct 04 '22 04:10

Sunil