Node.js – dnsPromises.lookupService() Method


The dns.lookupService() method resolves the given address and port into a hostname and service. This method uses the operating system’s underlying getnameinfo implementation.

A TypeError will be thrown if the address is not a valid IP address. The difference between the dnsPromises and dns module is that dnsPromises provides an alternative way to asynchronous DNS methods that return Promise objects instead of callbacks.

Syntax

dnsPromises.lookupService(address, port)

Parameters

  • address – This parameter takes input for the IP address that needs to be resolved.

  • port – This parameter takes input for the port number that is attached with the IP address.

Example 1

Create a file with the name "lookupService.js" and copy the following code snippet. After creating the file, use the command "node lookupService.js" to run this code.

// dns.lookupService() Demo Example

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

// Passing the IP address and port
dnsPromises.lookupService('127.0.0.1', 22).then((response) => {
   console.log(response.hostname, response.service);
});

Output

localhost ssh

Example 2

// dns.lookupService() Demo Example

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

// Passing the below options to lookup
const options = {
   //IPv4
   family: 4,
   hints: dns.ADDRCONFIG | dns.V4MAPPED,
};

dnsPromises.lookup('tutorialspoint.com', options).then((response) =>
{
   if(response){
      console.log(response);

      // Passing dns value to lookupservice
      dnsPromises.lookupService(response.address, 80).then((res) => {
         console.log(res.hostname, res.service);
      });
   }
});

Output

C:\home
ode>> node lookupService.js { address: '95.217.74.146', family: 4 } static.146.74.217.95.clients.your-server.de http

Updated on: 29-Oct-2021

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements