解决android的linux deploy下ping: localhost不通提示 Name or service not known,未知的名称或服务以及/etc/hosts不生效的问题

遇到了Can not connect to the Service chromedriver的问题,网上一查发现是localhost无法解析的问题
Can not connect to the Service chromedriver的解决方法
尝试ping了一下localhost,返回:

localhost:未知的名称或服务

改成英文版ping了一下locaohost,返回

localhost name or service not known

去/etc/hosts里面查了一下,发现文件正常:

127.0.0.1	localhost linuxdeploy
::1		localhost ip6-localhost ip6-loopback
ff02::1		ip6-allnodes
ff02::2		ip6-allrouters
180.101.49.11 	www.baidu.com
180.101.49.11	www.a.shifen.com
130.89.148.12 ftp.debian.org
127.0.0.1 fuck

尝试ping了下fuck,发现也是返回未知的名称或服务。
但是ping www.baidu.com却可以ping通。
之后查了一下linux下dns查询的原理。
按照这篇文章(https://zhuanlan.zhihu.com/p/42898476
)的说法,使用strace能看到dns查询的时候系统读取了/etc/hosts文件比如:

open("/etc/hosts", O_RDONLY|O_CLOEXEC)  = 4

之后使用命令strace -f ping -c1 localhost调试这个程序的系统调用,结果并没有发现系统读取了发现了/etc/hosts,反而发现这样一个报错:

connect(5, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
close(5)                                = 0
openat(AT_FDCWD, "/etc/nsswitch.conf", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat64("/etc/resolv.conf", {st_mode=S_IFREG|0644, st_size=52, ...}) = 0
openat(AT_FDCWD, "/etc/host.conf", O_RDONLY|O_CLOEXEC) = 5
fstat64(5, {st_mode=S_IFREG|0644, st_size=9, ...}) = 0
read(5, "multi on\n", 4096)             = 9
read(5, "", 4096)                       = 0
close(5)                                = 0

注意到其中读取了/etc/nsswitch.conf文件但是却报了错,表示找不到这个文件。
去系统里看了一下,果然没有这个文件。
我这个系统是debian系统,去debian的man page上面查了查,这个文件应该是自带的。
又从这里(https://blog.51cto.com/wujunfeng/1104498)了解到:
/etc/nsswitch.conf 其中的hosts:选项指定了系统dns的查询方式,比如:

hosts: dns files
表示只在DNS失效时候才使用/etc/hosts文件
hosts: dns
表示只用DNS解析主机
host: files
表示只用/etc/hosts文件解析主机
hosts: files dns
将使用/etc/hosts文件解析主机,表示如果无法解析主机名将使用DNS。

看来或许是这个文件缺失导致的localhost无法解析。
使用以下命令搜索了一下系统中有没有软件包带有nsswitch.conf 这个文件:

sudo apt-get install apt-file
apt-file update
apt-file search nsswitch.conf

发现glibc-source: /usr/src/glibc/debian/local/etc/nsswitch.conf在这里插入图片描述
于是直接把这个复制过去。

cp  /usr/src/glibc/debian/local/etc/nsswitch.conf /etc/

之后尝试ping localhost就可以通了。

猜你喜欢

转载自blog.csdn.net/fjh1997/article/details/114107380
今日推荐