Node.js – dns.lookup() 方法


dns.lookup() 方法將主機名(例如,tutorialspoint.com)解析為找到的第一個 A(IPv4)或 AAAA(IPv6)記錄。options 下可用的屬性是可選的。dns.lookup() 與 DNS 協議無關。該實現使用一個作業系統工具,該工具可以將名稱與地址關聯起來,反之亦然。

語法

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

引數

以上引數定義如下:

  • hostname – 這是您要查詢 DNS 值的網站主機名。

  • options – 它可以包含以下選項

    • family – 它只能取值 4、6 或 0。“0”表示返回 IPv4 和 IPv6 兩個地址。

    • hints – 它啟用一個或多個 getAddrinfoflags

    • all – 當此值設定為 true 時,回撥將所有解析的地址返回到陣列中,否則返回單個地址。

    • verbatim – 當設定為 True 時,回撥按 DNS 解析器返回的相同順序返回。

  • callback – 它將捕獲任何錯誤。

示例 1

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

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

輸出

address: undefined family: IPvundefined

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

輸出

addresses: undefined

更新於: 2021-10-29

572 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.