NodeJS 有没有办法绕过 Linux 的/etc/hosts 文件?
例如,如果我的主机文件中有一个条目,例如: 127.0.0.1 example.com
我如何从 NodeJS 访问“真实的”example.com?
我不想临时修改/etc/hosts 来执行此操作,因为它可能会带来一些问题,并且不是一个干净的解决方案。
提前致谢!
最佳答案
一开始我认为不可能,但后来我偶然发现了一种方法 ignore the hosts file on Linux 。另外,我发现了一个DNS API内置于 Node.js 中。基本上,默认情况下,Node 遵循操作系统进行 DNS 查找(它将从 /etc/hosts
读取,如果不需要,根本不会进行 DNS 查询)。然而,Node 还公开了一种通过显式发出 DNS 请求来解析主机名的方法。这将为您提供您正在寻找的 IP 地址。
$ cat /etc/hosts
<snip>
127.0.0.1 google.com
$ ping google.com
PING google.com (127.0.0.1) 56(84) bytes of data.
...
这表明主机文件肯定正在工作。
const dns = require('dns')
// This will use the hosts file.
dns.lookup('google.com', function (err, res) {
console.log('This computer thinks Google is located at: ' + res)
})
dns.resolve4('google.com', function (err, res) {
console.log('A real IP address of Google is: ' + res[0])
})
这会按预期输出不同的值:
$ node host.js
This computer thinks Google is located at: 127.0.0.1
A real IP address of Google is: 69.77.145.253
请注意,我使用最新的 Node v8.0.0 对此进行了测试。然而,我查看了一些较旧的文档,该 API 至少自 v0.12 起就存在,因此,假设没有发生任何重大变化,这应该适用于您碰巧运行的任何版本的 Node。此外,将主机名解析为 IP 地址可能只是成功的一半。如果您尝试直接通过 IP 访问某些网站,它们的行为会很奇怪(或根本没有行为)。
关于node.js - NodeJS,绕过linux主机文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335176/