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

夙愿已清 提交于 2019-12-01 04:11:12

问题


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?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/10420317/java-inetaddress-gethostname-taking-a-very-long-time-to-execute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!