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
const dns = require('dns')
dns.lookup('testwsserver', function(err, result) {
console.log(result)
})
Run Code Online (Sandbox Code Playgroud)
只是为了建立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)
| 归档时间: |
|
| 查看次数: |
14741 次 |
| 最近记录: |