【问题标题】:How to resolve hostname to an ip address in node js如何将主机名解析为节点js中的IP地址
【发布时间】:2016-08-09 22:17:21
【问题描述】:

我需要将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

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

hostname = "testwsserver"
hostIP = getIP(hostname);
console.log(hostIP); // This should print 192.168.253.20

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

非常感谢您的帮助!

【问题讨论】:

    标签: javascript node.js ip-address hostname hosts


    【解决方案1】:

    NodeJS documentation - DNS 怎么样 - 你检查了吗?

    const dns = require('dns')
    
    dns.lookup('testwsserver', function(err, result) {
      console.log(result)
    })
    

    【讨论】:

      【解决方案2】:

      只是以 Krzysztof Safjanowski 的回答为基础,

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

      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)
      }
      

      【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2011-03-12
      • 1970-01-01
      • 2011-05-07
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 2013-01-29
      相关资源
      最近更新 更多