How to resolve hostname to an ip address in node js

有些话、适合烂在心里 提交于 2019-12-22 04:38:06

问题


I need to resolve hostname defined in hosts file to its corresponding IP address.

For example my host file look like this - "/etc/hosts"

127.0.0.1    ggns2dss81 localhost.localdomain localhost
::1     localhost6.localdomain6 localhost6
192.168.253.8    abcdserver
192.168.253.20   testwsserver

Now in my node.js, i can read content of this file, but i need to fetch for given hostname.

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

PS - npm pkg or any third party package cannot be installed on machine.

Help is much appreciated!!


回答1:


How about NodeJS documentation - DNS – have you checked it?

const dns = require('dns')

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


来源:https://stackoverflow.com/questions/36689536/how-to-resolve-hostname-to-an-ip-address-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!