Java – getCanonicalHostName is very slow

getCanonicalHostName is very slow… here is a solution to the problem.

getCanonicalHostName is very slow

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

The above line of code takes about 10 seconds to execute.

I added the IP and hostname in the etc\hosts file and still nothing changes.

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

How can I improve the efficiency of this line of code?

Solution

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

The delay itself occurs in the Inet6AddressImpl.getHostByAddr(byte[]addr) method (called by InetAddress.getCanonicalHostName()), which is native, so it’s hard to name other DNS-related situations.

Related Problems and Solutions