root@BJ-CentOS7 ~ # ping baidu.com
ping: unknown host baidu.com
root@BJ-CentOS7 ~ # ping -c 2 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=251 time=96.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=251 time=100 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 96.635/98.431/100.227/1.796 ms
root@BJ-CentOS7 ~ # nslookup baidu.com
Server: 183.60.83.19
Address: 183.60.83.19#53
Non-authoritative answer:
Name: baidu.com
Address: 123.125.115.110
Name: baidu.com
Address: 220.181.57.216
root@BJ-CentOS7 ~ # grep nameserver /etc/resolv.conf
nameserver 183.60.83.19
nameserver 183.60.82.98
这里查阅资料了解到,原来 ping 程序解析域名依赖于C库中的函数 gethostbyname() 和 gethostbyaddr(),而这里对应的配置文件 /etc/nsswitch.conf 中的hosts 配置项:
files 表示使用 /etc/hosts 和 /etc/network 配置文件
dns 表示使用 /etc/resolv.conf 文件中的 DNS解析地址
nis 表示查询NIS系统的配置信息
root@BJ-CentOS7 ~ # grep hosts /etc/nsswitch.conf
#hosts: db files nisplus nis dns
hosts: files
root@BJ-CentOS7 ~ # cat /etc/hosts
127.0.0.1 localhost localhost.localdomain VM_1_10_centos
root@BJ-CentOS7 ~ # ping -c 2 localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.023 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.035 ms
--- localhost ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.023/0.029/0.035/0.006 ms
验证发现果然写在 hosts 文件中的地址可以正常被 ping 程序解析,问题基本清楚,nslookup 是直接使用 /etc/resolv.conf 中的 DNS 服务器解析域名,而 ping 程序在没有在 /etc/nsswitch.conf 中的 hosts: dns 选项,所以无法解析 /etc/hosts 文件中不存在的解析记录
root@BJ-CentOS7 ~ # grep hosts /etc/nsswitch.conf
#hosts: db files nisplus nis dns
hosts: files dns
root@BJ-CentOS7 ~ # ping -c 2 baidu.com
PING baidu.com (220.181.57.216) 56(84) bytes of data.
64 bytes from 220.181.57.216: icmp_seq=1 ttl=250 time=9.05 ms
64 bytes from 220.181.57.216: icmp_seq=2 ttl=250 time=9.06 ms
--- baidu.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 9.051/9.057/9.063/0.006 ms