Node.js – dns.lookupService() 方法


dns.lookupService() 方法將給定的地址和埠解析為一個主機名和服務。此方法使用作業系統底層 getnameinfo 實現。如果地址不是一個有效的 IP 地址,將丟擲 TypeError

語法

dns.lookupService(address, port, callback)

引數

  • address - 該引數需要輸入一個需要解析的 IP 地址。

  • port - 該引數需要輸入一個連線到 IP 地址的埠號。

  • callback - 任何錯誤都將被它捕獲。

示例 1

建立名為 "lookupService.js" 的檔案並複製以下程式碼。建立檔案後,使用 "node lookupService.js" 命令來執行此程式碼,如下例所示

// dns.lookupService() Demo Example

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

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

輸出

它將產生以下輸出 -

localhost ssh

示例 2

我們來看另一示例 -

// dns.lookupService() Demo Example

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

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

dns.lookup('tutorialsPoint.com',
   options, (err, address, family) => {

      console.log('address:', address);
         if(err){
            console.log(err.stack);
         } else{
         // Calling dns.lookupService() method
         // to retrieve details of IP address
         dns.lookupService(address, 80,(err, hostname, service) => {
            if(err){
               console.log(err.stack);
            }
            // Printing hostname and service
            // as callback
            console.log(hostname, service);
      });
   }
});

輸出

address: 157.90.94.102
tutorialspoint.com http

更新日期: 2021 年 11 月 24 日

182 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.