How to get ip address of any website using JS & nodejs? Code Example


Nodejs provides node:dns module which can be used to fetch DNS information of any website or host. In this article we will check out a code example to get ip address of any website using JS and node.

There are various methods in this module which returns information like –

  • Website IP Addresses
  • Family of IP like IPV4 or IPV6
  • Port number like 80 or 8888
  • Nameserver
  • Hostmaster
  • Priority
  • TTL
  • Type of record like A, AAAA, CNAME, MX, TXT etc.

Code Example

1. Using dns.lookup for single IP address

const dns = require('node:dns');

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

The output is –

address: "" family: IPv4
dns.lookup for website

But nodejs is running on multiple ip addresses and dns.lookup gave only one. If you want to get the list of all the ip addresses then use dns.resolve4.

2. Using dns.resolve4 for ip address list

const dns = require('node:dns');

dns.resolve4('', (err, addresses) => {
  if (err) throw err;

  console.log(`addresses: ${JSON.stringify(addresses)}`);

The output is –

addresses: ["",""]
dns.resolve4 on

3. Reverse lookup of host from ip address

If you want to get the host name from ip address then you can use dns.reverse function which accepts an ip address and returns the host name. Check this code –

const dns = require('node:dns');
const ipAddress = '' // IP of

dns.reverse(ipAddress, (err, hostnames) => {
    if (err) {
      throw err;
    console.log(`reverse for ${ipAddress}: ${JSON.stringify(hostnames)}`);

Output is –

reverse for [""]
dns.reverse for ip ->

4. Indepth DNS information

If you want to get information like nameservers, hostmaster, family, ttl, priority etc. you can use dns.resolveAny function. Check this code example –

const dns = require('node:dns');

dns.resolveAny('', (err, ret) => {
    if (err) {
      throw err;
    console.log(`All records: ${JSON.stringify(ret)}`);

Errors in DNS lookup

DNS lookup is not always successful. This is because of timeouts and restrictions from viewing the records by hosts. In this section we will see all the different kinds of errors you can get –

Error Code Details
NODATA When server returns no data
FORMERR Formatting error
SERVFAIL Some general failure
NOTFOUND Domain name not found
NOTIMP Not implemented
REFUSED Refused to process
BADQUERY Query is not right
BADNAME Host name is wrong
BADFAMILY Address family is wrong
BADRESP Response is wrong
CONNREFUSED Could not contact DNS server
TIMEOUT Timeout while processing
EOF End of file
FILE File processing error
NOMEM No memory available
DESTRUCTION Channel is destroyed
BADSTR Bad string
BADFLAGS Illegal flags
NONAME Not a valid host name
BADHINTS hints flags are invalid
NOTINITIALIZED library not initialized
LOADIPHLPAPI Error loading iphlpapi.dll
ADDRGETNETWORKPARAMS Could not find GetNetworkParams function
CANCELLED DNS query cancelled