3
InetAddress.getByName(ipAddress).getLocalHost().getCanonicalHostName();

The above line takes around 10seconds to execute.

I added the IP and hostname in etc\hosts file and still there is no change.

How does getCanonicalHostName work? Can I get the implementation of that method?

How do I increase the efficiency of this line of code?

Hulk Man
  • 153
  • 1
  • 15
  • Possible duplicate of https://stackoverflow.com/questions/33289695/inetaddress-getlocalhost-slow-to-run-30-seconds and https://stackoverflow.com/questions/10420317/java-inetaddress-gethostname-taking-a-very-long-time-to-execute – Red fx Oct 31 '17 at 09:17
  • Can u share the code for that function? – Hulk Man Oct 31 '17 at 09:25

2 Answers2

3

In my case the problem was caused by the Npcap driver, which I use for Wireshark. Disabling Npcap Loopback Adapter in Windows Control Panel\Network and Internet\Network Connections fixed the 9 seconds delay that I had.

The delay itself happens in the Inet6AddressImpl.getHostByAddr(byte[] addr) method (called by InetAddress.getCanonicalHostName()), which is native, so it's hard to say what's going on other than it's DNS related.

John29
  • 3,340
  • 3
  • 32
  • 50
0

When I Investigated the slow start of apache zookeeper on my windows, I had the same problem. zookeeper tries to get getCanonicalHostName which is very slow. So I tested the following code. The first log will output the ip which hostname will be obtained. I found that the ip(192.168.56.1) is not in my hosts file(C:\Windows\System32\drivers\etc\hosts).

InetAddress localHost = InetAddress.getLocalHost();
log.info(localHost);

String canonicalHostName = localHost.getCanonicalHostName();
log.info(canonicalHostName);

So I added the following line to hosts file, and the slow problem disappeared.

192.168.56.1        ip.of.vm
xia xiongjun
  • 141
  • 3
  • 6