简体   繁体   中英

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

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

const dns = require('dns')

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

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

Here's an example using standard modules , promises , and async/await :

import { default as dns } from 'dns';

async function getIP(hostname)
{
    let obj = await dns.promises.lookup(hostname).catch((error)=>
    {
        console.error(error);
    });
    return obj?.address;
}

async function main()
{
    let hostname = "stackoverflow.com";
    let hostIP = await getIP(hostname);
    console.log(`IP Address of ${hostname}:`, hostIP);
}
main();

You'd save this to a file ending with the extension mjs instead of js , so that node will know we're using the ES6 module's import statement instead of the commonJS require statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM