dns.lookup(hostname[, options], callback)
hostname<string>options<integer> | <Object>family<integer> 记录族。必须是4、6或0。值0表示同时返回 IPv4 和 IPv6 地址。默认值:0。hints<number> 一个或多个 支持的getaddrinfo标志。可以通过按位OR运算传递多个标志。all<boolean> 当设置为true时,回调会以数组形式返回所有解析的地址。否则,只返回一个地址。默认值:false。verbatim<boolean> 当值为true时,回调将按 DNS 解析器返回的顺序接收 IPv4 和 IPv6 地址。当值为false时,IPv4 地址会放在 IPv6 地址之前。默认值: 目前为false(地址会被重新排序),但预计在不久的将来会发生变化。默认值可以通过dns.setDefaultResultOrder()或--dns-result-order配置。新的代码应该使用{ verbatim: true }。
callback<Function>
将主机名(例如 'nodejs.org')解析为第一个找到的 A(IPv4)或 AAAA(IPv6)记录。所有 option 属性都是可选的。如果 options 是整数,则必须为 4 或 6 —— 如果未提供 options,则会返回找到的 IPv4 和 IPv6 地址。
🌐 Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or
AAAA (IPv6) record. All option properties are optional. If options is an
integer, then it must be 4 or 6 – if options is not provided, then IPv4
and IPv6 addresses are both returned if found.
当将 all 选项设置为 true 时,callback 的参数将变为 (err, addresses),其中 addresses 是包含 address 和 family 属性的对象数组。
🌐 With the all option set to true, the arguments for callback change to
(err, addresses), with addresses being an array of objects with the
properties address and family.
出现错误时,err 是一个 Error 对象,其中 err.code 是错误代码。请记住,err.code 不仅在主机名不存在时会被设置为 'ENOTFOUND',而且在查找以其他方式失败时也会如此,例如没有可用的文件描述符。
🌐 On error, err is an Error object, where err.code is the error code.
Keep in mind that err.code will be set to 'ENOTFOUND' not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.
dns.lookup() 不一定与 DNS 协议有关。
其实现使用了操作系统提供的功能,可以将名称与地址相互关联。
这种实现可能会对任何 Node.js 程序的行为产生微妙但重要的影响。
在使用 dns.lookup() 之前,请花一些时间参考 实现考虑部分。
用法示例:
🌐 Example usage:
const dns = require('node:dns');
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.com', options, (err, address, family) =>
console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.com', options, (err, addresses) =>
console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] 如果以其 util.promisify()ed 版本调用此方法,并且 all 未设置为 true,它将返回一个 Promise,该 Promise 包含具有 address 和 family 属性的 Object。
🌐 If this method is invoked as its util.promisify()ed version, and all
is not set to true, it returns a Promise for an Object with address and
family properties.