How does linux resolve wildcard locahost subdomains (e.g. : `ping test.localhost`) when `test.localhost` does not exist in /etc/hosts or dns server?

On Linux systems, the resolution is governed by /etc/nsswitch.conf that defines, for hostnames and other things, which sources of data to consult.

A typical configuration has:

hosts: files dns myhostname

If you remove myhostname, your test does not work: (I have to remove dns as well because my local recursive nameserver has a zone for localhost and hence replies)

# grep hosts: /etc/nsswitch.conf
hosts: files
# getent hosts foobar42.localhost

(no output)

# grep hosts: /etc/nsswitch.conf
hosts: files dns myhostname
# getent hosts foobar42.localhost
::1 localhost

This also shows that you don't need ping and in fact ping is almost always the wrong tool to use to troubleshoot. getent is the user facing tool to check resolution of anything defined in /etc/nsswitch.conf (and as bonus, getent favors IPv6 over IPv4 with the usual /etc/gai.conf setup, but you can force IPv4 with getent ahostsv4 ...

The myhostname "plugin" is documented at https://www.freedesktop.org/software/systemd/man/nss-myhostname.html

It says:

The precise hostnames resolved by this module are:

[..]

  • The hostnames "localhost" and "localhost.localdomain" (as well as any hostname ending in ".localhost" or ".localhost.localdomain") are resolved to the IP addresses 127.0.0.1 and ::1.

Mystery solved :-) (and the content of /etc/hosts is in fact irrelevant here)