How to get the IP address of a Website in Node.js?

Published December 6, 2020

To get the IP address of a website we can use either the resolve4() function for IPv4 addresses or the resolve6() function for IPv6 addresses from the dns module in Node.js.

Let's say our website is google.com,

// website URL
const url = "google.com";

Now let's use the resolve4() function from the dns module and pass the url as the first argument and a callback function as the second argument.

The callback function should be an error first callback function, in which:

  • the first parameter is of course an error object
  • the second parameter is an array of IPv4 addresses after the resolution

It can be done like this,

// require dns module
const dns = require("dns");

// website URL
const url = "google.com";

// get the IPv4 address
// using dns.resolve4() function
dns.resolve4(url, (err, addresses) => {
  // if any err
  // log to console
  if (err) {
    console.err(err);
    return;
  }

  // otherwise show the first IPv4 address
  // from the array
  console.log(addresses[0]); // eg: 64.233.191.113
});

See this example live in repl.it.

If you want to get the Time to live (TTL) of the request in seconds, you can pass an optional object with ttl set to boolean true {ttl: true} as the second argument to the resolve4() function like this,

// require dns module
const dns = require("dns");

// website URL
const url = "google.com";

// get the IPv4 address
// using dns.resolve4() function
// also set ttl to true in object
dns.resolve4(url, { ttl: true }, (err, addresses) => {
  // if any err
  // log to console
  if (err) {
    console.err(err);
    return;
  }

  // otherwise show the first IPv4 address
  // from the array
  // Also, the ttl for the request
  // is shown along with the address
  console.log(addresses[0]); // eg: { 64.233.191.113, ttl: 299}
});

If you want an IPv6 address instead of IPv4, you can use the resolve6() function instead of the resolve4() function and use the same pattern like this,

// require dns module
const dns = require("dns");

// website URL
const url = "google.com";

// get the IPv6 address
// using dns.resolve6() function
dns.resolve6(url, (err, addresses) => {
  // if any err
  // log to console
  if (err) {
    console.err(err);
    return;
  }

  // otherwise show the first IPv6 address
  // from the array
  console.log(addresses[0]); // eg: 2607:f8b0:4001:c03::71
});

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter