Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get ip address by domain with dns.lookup() node.js

Referring to this documentation I am getting the ip address from domain name inside console.log the code looks like so:

const dns = require('dns');

dns.lookup('iana.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});

Output of console.log is fine. However I can't get address outside that scope. The return statement of the dns.lookup function is an object.

What I've tried so far:

const ipAddress = dns.lookup("www.aWebSiteName.am", (err, address, family) => {
  if(err) throw err;
  return address;
});

console.log(ipAddress);

I am getting:

GetAddrInfoReqWrap {
  callback: [Function],
  family: 0,
  hostname: 'www.aWebSiteName.am',
  oncomplete: [Function: onlookup] }
like image 553
undefinedUser Avatar asked Feb 26 '19 13:02

undefinedUser


People also ask

What is the syntax of DNS lookup function?

The dns. lookup() method is an inbuilt application programming interface of the dns module which is used to resolve IP addresses of the specified hostname for given parameters into the first found A (IPv4) or AAAA (IPv6) record. Syntax: dns.lookup( hostname, options, callback )

How do I lookup an IP address from a domain?

Type "nslookup google.com" - this command will show DNS information of google.com, replace google.com with your own domain name. First two lines show DNS resolver information. Second line will be IP address you will be looking for.

How do I run a DNS lookup?

Go to Start and type cmd in the search field to open the command prompt. Alternatively, go to Start > Run > type cmd or command. Type nslookup and hit Enter. The displayed information will be your local DNS server and its IP address.


2 Answers

You can not because dns.lookup() function is working async.

Though the call to dns.lookup() will be asynchronous from JavaScript's perspective, it is implemented as a synchronous call to getaddrinfo(3) that runs on libuv's threadpool. This can have surprising negative performance implications for some applications, see the UV_THREADPOOL_SIZE documentation for more information.

There are different ways to take the result. Welcome to JS world!

Callback

dns.lookup("www.aWebSiteName.am", (err, address, family) => {
  if(err) throw err;
  printResult(address);
});

function printResult(address){
   console.log(address);
}

Promise

const lookupPromise = new Promise((resolve, reject) => {
    dns.lookup("www.aWebSiteName.am", (err, address, family) => {
        if(err) reject(err);
        resolve(address);
    });
});

lookupPromise().then(res => console.log(res)).catch(err => console.error(err));

Promise async/await

async function lookupPromise(){
    return new Promise((resolve, reject) => {
        dns.lookup("www.aWebSiteName.am", (err, address, family) => {
            if(err) reject(err);
            resolve(address);
        });
   });
};

try{
    cons address = await lookupPromise();
}catch(err){
    console.error(err);
}
like image 61
hurricane Avatar answered Oct 03 '22 18:10

hurricane


This is normal because "dns.lookup" is executed asynchronously

So you can't just use the returned value of the function

You need to do your logic inside the callback or make an helper to promisfy the function and execute it in async function with await.

Something like this:

function lookup(domain) {
  return new Promise((resolve, reject) => {
    dns.lookup(address, (err, address, family) => {
      if (err) {
        reject(err)
      } else {
        resolve({ address, family })
      }
    })
  })
}

async function test() {
  let ipAddress = await lookup(("www.aWebSiteName.am");
}

EDIT:

You can also use:

const dns = require('dns');
dnsPromises = dns.promises;

async function test() {
  let data = await dnsPromises.lookup(("www.aWebSiteName.am");
}
like image 22
Tristan De Oliveira Avatar answered Oct 03 '22 18:10

Tristan De Oliveira