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?
An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.
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.
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.
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.
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
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