为什么 *.localhost 在 Ubuntu 上可以自动解析,但在 MacOS 上却不能?

为什么 *.localhost 在 Ubuntu 上可以自动解析,但在 MacOS 上却不能?

我在 Ubuntu 和 MacOS 上都有相同的 hosts 文件。

127.0.0.1   localhost

在 Ubuntu 上:

my-ubuntu$ ping foo.localhost
PING foo.localhost(ip6-localhost (::1)) 56 data bytes
64 bytes from ip6-localhost (::1): icmp_seq=1 ttl=64 time=0.129 ms
64 bytes from ip6-localhost (::1): icmp_seq=2 ttl=64 time=0.073 ms
64 bytes from ip6-localhost (::1): icmp_seq=3 ttl=64 time=0.059 ms
...

在 MacOs 上:

my-mac$ ping foo.localhost
ping: cannot resolve foo.localhost: Unknown host

为什么 localhost 的子域名在 Ubuntu 上可以自动解析,但在 MacOS 上却不能?

答案1

原因很可能是 systemd-resolvd。

检查配置:

root@sf:~# grep localhost /etc/hosts
127.0.0.1   localhost
::1     ip6-localhost ip6-loopback
root@sf:~# grep nameserver /etc/resolv.conf
nameserver 127.0.0.53

127.0.0.53 是 systemd 解析器。

现在执行 ping 操作:

root@sf:~# ping -c 1 foo.localhost
PING foo.localhost(ip6-localhost (::1)) 56 data bytes
64 bytes from ip6-localhost (::1): icmp_seq=1 ttl=64 time=0.035 ms
--- foo.localhost ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.035/0.035/0.035/0.000 ms

root@sf:~# ping -c 1 serverfault.com
PING serverfault.com (151.101.129.69) 56(84) bytes of data.
64 bytes from 151.101.129.69 (151.101.129.69): icmp_seq=1 ttl=59 time=16.8 ms
--- serverfault.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 16.802/16.802/16.802/0.000 ms

是的,它的工作原理与您的 ping 完全一样。

现在从 systemd 解析器切换到我的 LAN 的 dns 缓存:

root@sf:~# sed -i '/nameserver/s,.*,nameserver 192.168.101.1,' /etc/resolv.conf
root@sf:~# grep nameserver /etc/resolv.conf
nameserver 192.168.101.1

再次执行 ping 操作:

root@sf:~# ping -c 1 foo.localhost
ping: foo.localhost: Name or service not known
root@sf:~# ping -c 1 serverfault.com
PING serverfault.com (151.101.129.69) 56(84) bytes of data.
64 bytes from 151.101.129.69 (151.101.129.69): icmp_seq=1 ttl=59 time=16.4 ms
--- serverfault.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 16.426/16.426/16.426/0.000 ms

瞧!

相关内容