域名系统


【DNS】

源代码: lib/dns.js

node:dns 模块用于实现名称解析。例如,可以使用它来查询主机名的 IP 地址。

【The node:dns module enables name resolution. For example, use it to look up IP addresses of host names.】

虽然以 域名系统 (DNS) 命名,但它并不总是使用 DNS 协议进行查询。dns.lookup() 使用操作系统功能来执行名称解析。它可能不需要进行任何网络通信。要像同一系统上的其他应用那样执行名称解析,请使用 dns.lookup()

【Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. dns.lookup() uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use dns.lookup().】

import dns from 'node:dns';

dns.lookup('example.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6const dns = require('node:dns');

dns.lookup('example.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});
// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6

node:dns 模块中的所有其他函数都会连接到实际的 DNS 服务器以执行名称解析。它们始终使用网络来执行 DNS 查询。这些函数不会使用 dns.lookup() 所使用的同一组配置文件(例如 /etc/hosts)。使用这些函数可以始终执行 DNS 查询,绕过其他名称解析机制。

【All other functions in the node:dns module connect to an actual DNS server to perform name resolution. They will always use the network to perform DNS queries. These functions do not use the same set of configuration files used by dns.lookup() (e.g. /etc/hosts). Use these functions to always perform DNS queries, bypassing other name-resolution facilities.】

import dns from 'node:dns';

dns.resolve4('archive.org', (err, addresses) => {
  if (err) throw err;

  console.log(`addresses: ${JSON.stringify(addresses)}`);

  addresses.forEach((a) => {
    dns.reverse(a, (err, hostnames) => {
      if (err) {
        throw err;
      }
      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
    });
  });
});const dns = require('node:dns');

dns.resolve4('archive.org', (err, addresses) => {
  if (err) throw err;

  console.log(`addresses: ${JSON.stringify(addresses)}`);

  addresses.forEach((a) => {
    dns.reverse(a, (err, hostnames) => {
      if (err) {
        throw err;
      }
      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
    });
  });
});

请参阅 实现考虑部分 以获取更多信息。

【See the Implementation considerations section for more information.】