Networking

當 /etc/hosts 或 dns 伺服器中不存在 test.localhost 時,linux 如何解析萬用字元 locahost 子域(例如:ping test.localhost)?

  • June 3, 2021

例如在/etc/hosts文件為空的 ubuntu 20.04 LTS 中:

>>> cat /etc/hosts
127.0.0.1       localhost

ping仍然適用於本地主機的任何子域:

>>> ping test.localhost
PING test.localhost(ip6-localhost (::1)) 56 data bytes
64 bytes from ip6-localhost (::1): icmp_seq=1 ttl=64 time=0.058 ms
64 bytes from ip6-localhost (::1): icmp_seq=2 ttl=64 time=0.049 ms
^C
--- test.localhost ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1028ms
rtt min/avg/max/mdev = 0.049/0.053/0.058/0.004 ms

或者:

>>> ping test2.localhost
PING test2.localhost(ip6-localhost (::1)) 56 data bytes
64 bytes from ip6-localhost (::1): icmp_seq=1 ttl=64 time=0.042 ms
64 bytes from ip6-localhost (::1): icmp_seq=2 ttl=64 time=0.063 ms
^C
--- test2.localhost ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1004ms
rtt min/avg/max/mdev = 0.042/0.052/0.063/0.010 ms

這個答案暗示涉及系統解析器,但它實際上是如何發生的?

如果localhostin/etc/hosts被替換為另一個值,則子域不再起作用:

>>> cat /etc/hosts
127.0.0.1       testname


>>> ping testname
PING testname (127.0.0.1) 56(84) bytes of data.
64 bytes from testname (127.0.0.1): icmp_seq=1 ttl=64 time=0.071 ms
64 bytes from testname (127.0.0.1): icmp_seq=2 ttl=64 time=0.080 ms
^C
--- testname ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1011ms
rtt min/avg/max/mdev = 0.071/0.075/0.080/0.004 ms

>>> ping new.testname
ping: new.testname: Name or service not known

為什麼它適用於 localhost 而沒有其他主機名,它是如何實現的?

在 Linux 系統上,解析度由/etc/nsswitch.conf主機名和其他事物定義的要查閱的數據源控制。

一個典型的配置有:

hosts: files dns myhostname

如果您刪除myhostname,您的測試將不起作用:(我也必須刪除dns,因為我的本地遞歸名稱伺服器有一個區域localhost,因此會回复)

# 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

這也表明您不需要ping並且實際上ping幾乎總是用於故障排除的錯誤工具。getent是一個面向使用者的工具,用於檢查中定義的任何內容的解析度/etc/nsswitch.conf (並且作為獎勵,getent使用通常的設置支持 IPv6 而不是 IPv4 /etc/gai.conf,但您可以強制使用 IPv4getent ahostsv4 ...

myhostname外掛”記錄在https://www.freedesktop.org/software/systemd/man/nss-myhostname.html

它說:

此模組解析的精確主機名是:

$$ .. $$

  • 主機名“localhost”和“localhost.localdomain”(以及任何以“.localhost”或“.localhost.localdomain”結尾的主機名)被解析為 IP 地址 127.0.0.1 和 ::1。

謎團解決了:- /etc/hosts)(實際上這裡的內容無關緊要)

引用自:https://serverfault.com/questions/1065513