Why does it take longer to ping by hostname than by IP address?

I've noticed that pinging by hostname is slower than using the IP address. For example, in the Linux command line:

$ time ping google.com -c 1
PING google.com (150.101.213.160) 56(84) bytes of data.
64 bytes from 150.101.213.160: icmp_seq=1 ttl=61 time=14.4 ms

--- google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 14.425/14.425/14.425/0.000 ms

real    0m5.251s
user    0m0.003s
sys 0m0.005s

$ time ping 150.101.213.160 -c 1
PING 150.101.213.160 (150.101.213.160) 56(84) bytes of data.
64 bytes from 150.101.213.160: icmp_seq=1 ttl=61 time=14.5 ms

--- 150.101.213.160 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 14.537/14.537/14.537/0.000 ms

real    0m0.019s
user    0m0.001s
sys 0m0.004s

I thought at first it was the DNS server taking a while to resolve, but when I ping by hostname, the first line appears almost immediately, showing that the IP address has already been determined. The five-second pause is after this DNS resolution, just before the (first) ping is received.


Solution 1:

The delay is caused by ping trying to resolve the IP address back to a name1, by looking up 160.213.101.150.in-addr.arpa (reverse DNS).

Normally the reply (whether success or nxdomain) should be instant, but it could be that it wasn't cached by your ISP and the authoritative servers for 213.101.150.in-addr.arpa were having problems at that time.

It might also be caused by misconfiguration or just bugs in certain DNS servers. If you see this delay happening every single time, it might be that your DNS resolver isn't properly caching replies when it should (even negative replies are cacheable).

When using the ping from iputils, add the -n option to avoid reverse-DNS lookups.


1 It's a domain name or a host name, not an URL; it doesn't specify any particular protocol or resource. http://google.com would be an URL. http://150.101.213.160 would be an URL too.