How to resolve hostname to an ip address in node js
28,101
Solution 1
How about NodeJS documentation - DNS – have you checked it?
const dns = require('dns')
dns.lookup('testwsserver', function(err, result) {
console.log(result)
})
Solution 2
Just to build on Krzysztof Safjanowski's answer,
you can also use the builtin promisify utility to convert it to a promise rather than a callback.
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)
}
Author by
Abhilash Kant
Updated on August 26, 2020Comments
-
Abhilash Kant over 3 years
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 givenhostname
.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!!
-
oligofren over 2 yearsA bit superfluous when the
dns
module already has Promise support built-in :) Just doconst {lookup} = require('dns').promises
.