abhi9393 abhi9393 - 1 month ago 10
Javascript Question

How to resolve hostname to an ip address in node js

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!!

Answer
const dns = require('dns')

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