例如在/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
这个答案暗示涉及系统解析器,但它实际上是如何发生的?
如果localhost
in/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
主机名和其他内容定义的要查阅的数据源控制。一个典型的配置有:
如果您删除
myhostname
,您的测试将不起作用:(我也必须删除dns
,因为我的本地递归名称服务器有一个区域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它说:
谜团解决了:-
/etc/hosts
)(实际上这里的内容无关紧要)