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

3

7

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?

Chlamys answered 2/5, 2012 at 19:25 Comment(1)
How long is "quite some time" in your cases?Machinate
E
13

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.

Equality answered 2/5, 2012 at 19:30 Comment(0)
F
1

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

Forney answered 2/5, 2012 at 19:33 Comment(0)
R
0

toString() seems to be faster:

given an InetAddress ia or InterfaceAddress ia,

System.out.println ( ia.toString() ) will show a string containing your ipAddress faster than ia.getHostName()

You can then use ia.toString().substring to extract it.

I don't know why.

Reverberation answered 16/8, 2014 at 16:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.