Node.js – dns.lookup() Method


The dns.lookup() method resolves the host name (e.g., tutorialspoint.com) into the first found A IPv4) or AAAA (IPv6) record. The properties available under the options are optional. dns.lookup() does not have anything to do with the DNS protocol. The implementation uses an OS facility that can associate names with addresses and vice versa.

Syntax

dns.lookup(hostname, [options], callback)

Parameters

The above parameters are defined as below −

  • hostname – This is the website hostname for which you want to look up the DNS values.

  • options – It can have the following options

    • family – It can have the values 4, 6, or 0 only. The value "0" indicates that both the addresses IPv4 and IPv6 are returned.

    • hints – It enables one or more getAddrinfoflags.

    • all – The callback returns all the resolved addresses in an array when this value is set to true, else a single address is returned.

    • verbatim – The callback is returned in the same order the DNS resolver returned them when set to True.

  • callback – It will catch errors, if any.

Example 1

Create a file "lookup.js" and copy the following code snippet. After creating the file use the below command "node lookup.js" to run this code.

// dns.lookup() method Demo Example

// Importing the dns module
const dns = require('dns');

// Passing some options for dns.lookup()
const options = {
   family: 6,
   hints: dns.ADDRCONFIG | dns.V4MAPPED,
};

dns.lookup('tutorialspoint.com', options, (err, address, family) =>
   // This will display the address family and its value
   console.log('address: %j family: IPv%s', address, family));

Output

address: undefined family: IPvundefined

Example 2

// dns.lookup() method Demo Example
// Importing the dns module

const dns = require('dns');

// Initializing some options
const options = {
   family: 6,
   hints: dns.ADDRCONFIG | dns.V4MAPPED,
};

// Result will be an array, when all the options are true
options.all = true;
dns.lookup('tutorialspoint.com', options, (err, addresses) =>
   console.log('addresses: %j', addresses));

Output

addresses: undefined

Updated on: 29-Oct-2021

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements