如何将主机名解析为节点js中的IP地址

abh*_*393 7 javascript hosts ip-address hostname node.js

我需要将hosts文件中定义的主机名解析为其对应的IP地址.

例如我的主机文件看起来像这样 - "/ etc/hosts"

127.0.0.1    ggns2dss81 localhost.localdomain localhost
::1     localhost6.localdomain6 localhost6
192.168.253.8    abcdserver
192.168.253.20   testwsserver
Run Code Online (Sandbox Code Playgroud)

现在在我node.js,我可以阅读这个文件的内容,但我需要获取给定的hostname.

hostname = "testwsserver"
hostIP = getIP(hostname);
console.log(hostIP); // This should print 192.168.253.20
Run Code Online (Sandbox Code Playgroud)

PS - npm pkg或任何第三方软件包无法安装在计算机上.

非常感谢帮助!!

Krz*_*ski 20

NodeJS文档怎么样- DNS - 你检查过吗?

const dns = require('dns')

dns.lookup('testwsserver', function(err, result) {
  console.log(result)
})
Run Code Online (Sandbox Code Playgroud)


Ben*_*ing 8

只是为了建立Krzysztof Safjanowski的答案,

您还可以使用内置的promisify实用程序将其转换为承诺而不是回调。

const util = require('util');
const dns = require('dns');
const lookup = util.promisify(dns.lookup);

try {
  result = await lookup('google.com')
  console.log(result)
} catch (error) {
  console.error(error)
}
Run Code Online (Sandbox Code Playgroud)

  • 当 `dns` 模块已经内置了 [Promise 支持](https://nodejs.org/docs/latest-v16.x/api/dns.html) 时有点多余:) 只需执行 `const {lookup} = require('dns').promises`。 (6认同)