How to find the hostname of an IP using /etc/hosts if it has the mapping on Linux?

Common DNS queries like ping will first get the IP of a hostname if it exists in /etc/hosts.

How to find the hostname of an IP using /etc/hosts if it has the mapping on Linux?

Multiple tools on Linux can do the "reverse" checking using /etc/hosts file. For example, if we have a line 192.0.2.1 test in the /etc/hosts, we can query the host name from the IP as follows.

Use getent

getent hosts: When one or more arguments are provided, it will pass each key to gethostbyaddr() or gethostbyname2(), depending on whether a call to inet_pton() indicates that the argument is an IPv6 or IPv4 address or not, and display the result.

$ getent hosts test
192.0.2.1       test

Use host

If host is given a dotted-decimal IPv4 address or a colon-delimited IPv6 address, host will by default perform a reverse lookup for that address.

$ host 192.0.2.1
1.2.0.192.in-addr.arpa domain name pointer test.