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

czchlong picture czchlong · May 2, 2012 · Viewed 8.1k times · Source

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?

Answer

maerics picture maerics · May 2, 2012

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.