Node.js – dnsPromises.lookupService() 方法


dns.lookupService() 方法解析給定的地址和埠成一個主機名稱和服務。此方法使用作業系統底層的 getnameinfo 實現。

如果地址無效 IP 地址,將引發 TypeErrordnsPromisesdns 模組的區別在於,dnsPromises 提供了一個替代非同步 DNS 方法,該方法返回 Promise 物件而不是回撥。

語法

dnsPromises.lookupService(address, port)

引數

  • address – 此引數接收需要解析的 IP 地址。

  • port – 此引數接收與 IP 地址關聯的埠號。

示例 1

建立一個名為 "lookupService.js" 的檔案並複製以下程式碼片段。建立檔案後,使用命令 "node lookupService.js" 執行此程式碼。

// 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);
});

輸出

localhost ssh

示例 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);
      });
   }
});

輸出

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

更新於: 2021-10-29

54 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.