• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# DNS
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/dns.js -->
8
9The `dns` module enables name resolution. For example, use it to look up IP
10addresses of host names.
11
12Although named for the [Domain Name System (DNS)][], it does not always use the
13DNS protocol for lookups. [`dns.lookup()`][] uses the operating system
14facilities to perform name resolution. It may not need to perform any network
15communication. To perform name resolution the way other applications on the same
16system do, use [`dns.lookup()`][].
17
18```js
19const dns = require('dns');
20
21dns.lookup('example.org', (err, address, family) => {
22  console.log('address: %j family: IPv%s', address, family);
23});
24// address: "93.184.216.34" family: IPv4
25```
26
27All other functions in the `dns` module connect to an actual DNS server to
28perform name resolution. They will always use the network to perform DNS
29queries. These functions do not use the same set of configuration files used by
30[`dns.lookup()`][] (e.g. `/etc/hosts`). Use these functions to always perform
31DNS queries, bypassing other name-resolution facilities.
32
33```js
34const dns = require('dns');
35
36dns.resolve4('archive.org', (err, addresses) => {
37  if (err) throw err;
38
39  console.log(`addresses: ${JSON.stringify(addresses)}`);
40
41  addresses.forEach((a) => {
42    dns.reverse(a, (err, hostnames) => {
43      if (err) {
44        throw err;
45      }
46      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
47    });
48  });
49});
50```
51
52See the [Implementation considerations section][] for more information.
53
54## Class: `dns.Resolver`
55<!-- YAML
56added: v8.3.0
57-->
58
59An independent resolver for DNS requests.
60
61Creating a new resolver uses the default server settings. Setting
62the servers used for a resolver using
63[`resolver.setServers()`][`dns.setServers()`] does not affect
64other resolvers:
65
66```js
67const { Resolver } = require('dns');
68const resolver = new Resolver();
69resolver.setServers(['4.4.4.4']);
70
71// This request will use the server at 4.4.4.4, independent of global settings.
72resolver.resolve4('example.org', (err, addresses) => {
73  // ...
74});
75```
76
77The following methods from the `dns` module are available:
78
79* [`resolver.getServers()`][`dns.getServers()`]
80* [`resolver.resolve()`][`dns.resolve()`]
81* [`resolver.resolve4()`][`dns.resolve4()`]
82* [`resolver.resolve6()`][`dns.resolve6()`]
83* [`resolver.resolveAny()`][`dns.resolveAny()`]
84* [`resolver.resolveCname()`][`dns.resolveCname()`]
85* [`resolver.resolveMx()`][`dns.resolveMx()`]
86* [`resolver.resolveNaptr()`][`dns.resolveNaptr()`]
87* [`resolver.resolveNs()`][`dns.resolveNs()`]
88* [`resolver.resolvePtr()`][`dns.resolvePtr()`]
89* [`resolver.resolveSoa()`][`dns.resolveSoa()`]
90* [`resolver.resolveSrv()`][`dns.resolveSrv()`]
91* [`resolver.resolveTxt()`][`dns.resolveTxt()`]
92* [`resolver.reverse()`][`dns.reverse()`]
93* [`resolver.setServers()`][`dns.setServers()`]
94
95### `Resolver([options])`
96<!-- YAML
97added: v8.3.0
98changes:
99  - version: v12.18.3
100    pr-url: https://github.com/nodejs/node/pull/33472
101    description: The constructor now accepts an `options` object.
102                 The single supported option is `timeout`.
103-->
104
105Create a new resolver.
106
107* `options` {Object}
108  * `timeout` {integer} Query timeout in milliseconds, or `-1` to use the
109    default timeout.
110
111### `resolver.cancel()`
112<!-- YAML
113added: v8.3.0
114-->
115
116Cancel all outstanding DNS queries made by this resolver. The corresponding
117callbacks will be called with an error with code `ECANCELLED`.
118
119## `dns.getServers()`
120<!-- YAML
121added: v0.11.3
122-->
123
124* Returns: {string[]}
125
126Returns an array of IP address strings, formatted according to [RFC 5952][],
127that are currently configured for DNS resolution. A string will include a port
128section if a custom port is used.
129
130<!-- eslint-disable semi-->
131```js
132[
133  '4.4.4.4',
134  '2001:4860:4860::8888',
135  '4.4.4.4:1053',
136  '[2001:4860:4860::8888]:1053'
137]
138```
139
140## `dns.lookup(hostname[, options], callback)`
141<!-- YAML
142added: v0.1.90
143changes:
144  - version: v8.5.0
145    pr-url: https://github.com/nodejs/node/pull/14731
146    description: The `verbatim` option is supported now.
147  - version: v1.2.0
148    pr-url: https://github.com/nodejs/node/pull/744
149    description: The `all` option is supported now.
150-->
151
152* `hostname` {string}
153* `options` {integer | Object}
154  * `family` {integer} The record family. Must be `4`, `6`, or `0`. The value
155    `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:**
156    `0`.
157  * `hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple
158    flags may be passed by bitwise `OR`ing their values.
159  * `all` {boolean} When `true`, the callback returns all resolved addresses in
160    an array. Otherwise, returns a single address. **Default:** `false`.
161  * `verbatim` {boolean} When `true`, the callback receives IPv4 and IPv6
162    addresses in the order the DNS resolver returned them. When `false`,
163    IPv4 addresses are placed before IPv6 addresses.
164    **Default:** currently `false` (addresses are reordered) but this is
165    expected to change in the not too distant future.
166    New code should use `{ verbatim: true }`.
167* `callback` {Function}
168  * `err` {Error}
169  * `address` {string} A string representation of an IPv4 or IPv6 address.
170  * `family` {integer} `4` or `6`, denoting the family of `address`, or `0` if
171    the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a
172    bug in the name resolution service used by the operating system.
173
174Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
175AAAA (IPv6) record. All `option` properties are optional. If `options` is an
176integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
177and IPv6 addresses are both returned if found.
178
179With the `all` option set to `true`, the arguments for `callback` change to
180`(err, addresses)`, with `addresses` being an array of objects with the
181properties `address` and `family`.
182
183On error, `err` is an [`Error`][] object, where `err.code` is the error code.
184Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
185the host name does not exist but also when the lookup fails in other ways
186such as no available file descriptors.
187
188`dns.lookup()` does not necessarily have anything to do with the DNS protocol.
189The implementation uses an operating system facility that can associate names
190with addresses, and vice versa. This implementation can have subtle but
191important consequences on the behavior of any Node.js program. Please take some
192time to consult the [Implementation considerations section][] before using
193`dns.lookup()`.
194
195Example usage:
196
197```js
198const dns = require('dns');
199const options = {
200  family: 6,
201  hints: dns.ADDRCONFIG | dns.V4MAPPED,
202};
203dns.lookup('example.com', options, (err, address, family) =>
204  console.log('address: %j family: IPv%s', address, family));
205// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
206
207// When options.all is true, the result will be an Array.
208options.all = true;
209dns.lookup('example.com', options, (err, addresses) =>
210  console.log('addresses: %j', addresses));
211// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
212```
213
214If this method is invoked as its [`util.promisify()`][]ed version, and `all`
215is not set to `true`, it returns a `Promise` for an `Object` with `address` and
216`family` properties.
217
218### Supported getaddrinfo flags
219<!-- YAML
220changes:
221  - version: v12.17.0
222    pr-url: https://github.com/nodejs/node/pull/32183
223    description: Added support for the `dns.ALL` flag.
224-->
225
226The following flags can be passed as hints to [`dns.lookup()`][].
227
228* `dns.ADDRCONFIG`: Limits returned address types to the types of non-loopback
229addresses configured on the system. For example, IPv4 addresses are only
230returned if the current system has at least one IPv4 address configured.
231* `dns.V4MAPPED`: If the IPv6 family was specified, but no IPv6 addresses were
232found, then return IPv4 mapped IPv6 addresses. It is not supported
233on some operating systems (e.g FreeBSD 10.1).
234* `dns.ALL`: If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
235well as IPv4 mapped IPv6 addresses.
236
237## `dns.lookupService(address, port, callback)`
238<!-- YAML
239added: v0.11.14
240-->
241
242* `address` {string}
243* `port` {number}
244* `callback` {Function}
245  * `err` {Error}
246  * `hostname` {string} e.g. `example.com`
247  * `service` {string} e.g. `http`
248
249Resolves the given `address` and `port` into a host name and service using
250the operating system's underlying `getnameinfo` implementation.
251
252If `address` is not a valid IP address, a `TypeError` will be thrown.
253The `port` will be coerced to a number. If it is not a legal port, a `TypeError`
254will be thrown.
255
256On an error, `err` is an [`Error`][] object, where `err.code` is the error code.
257
258```js
259const dns = require('dns');
260dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
261  console.log(hostname, service);
262  // Prints: localhost ssh
263});
264```
265
266If this method is invoked as its [`util.promisify()`][]ed version, it returns a
267`Promise` for an `Object` with `hostname` and `service` properties.
268
269## `dns.resolve(hostname[, rrtype], callback)`
270<!-- YAML
271added: v0.1.27
272-->
273
274* `hostname` {string} Host name to resolve.
275* `rrtype` {string} Resource record type. **Default:** `'A'`.
276* `callback` {Function}
277  * `err` {Error}
278  * `records` {string[] | Object[] | Object}
279
280Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
281of the resource records. The `callback` function has arguments
282`(err, records)`. When successful, `records` will be an array of resource
283records. The type and structure of individual results varies based on `rrtype`:
284
285|  `rrtype` | `records` contains             | Result type | Shorthand method         |
286|-----------|--------------------------------|-------------|--------------------------|
287| `'A'`     | IPv4 addresses (default)       | {string}    | [`dns.resolve4()`][]     |
288| `'AAAA'`  | IPv6 addresses                 | {string}    | [`dns.resolve6()`][]     |
289| `'ANY'`   | any records                    | {Object}    | [`dns.resolveAny()`][]   |
290| `'CNAME'` | canonical name records         | {string}    | [`dns.resolveCname()`][] |
291| `'MX'`    | mail exchange records          | {Object}    | [`dns.resolveMx()`][]    |
292| `'NAPTR'` | name authority pointer records | {Object}    | [`dns.resolveNaptr()`][] |
293| `'NS'`    | name server records            | {string}    | [`dns.resolveNs()`][]    |
294| `'PTR'`   | pointer records                | {string}    | [`dns.resolvePtr()`][]   |
295| `'SOA'`   | start of authority records     | {Object}    | [`dns.resolveSoa()`][]   |
296| `'SRV'`   | service records                | {Object}    | [`dns.resolveSrv()`][]   |
297| `'TXT'`   | text records                   | {string[]}  | [`dns.resolveTxt()`][]   |
298
299On error, `err` is an [`Error`][] object, where `err.code` is one of the
300[DNS error codes](#dns_error_codes).
301
302## `dns.resolve4(hostname[, options], callback)`
303<!-- YAML
304added: v0.1.16
305changes:
306  - version: v7.2.0
307    pr-url: https://github.com/nodejs/node/pull/9296
308    description: This method now supports passing `options`,
309                 specifically `options.ttl`.
310-->
311
312* `hostname` {string} Host name to resolve.
313* `options` {Object}
314  * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
315    When `true`, the callback receives an array of
316    `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings,
317    with the TTL expressed in seconds.
318* `callback` {Function}
319  * `err` {Error}
320  * `addresses` {string[] | Object[]}
321
322Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the
323`hostname`. The `addresses` argument passed to the `callback` function
324will contain an array of IPv4 addresses (e.g.
325`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
326
327## `dns.resolve6(hostname[, options], callback)`
328<!-- YAML
329added: v0.1.16
330changes:
331  - version: v7.2.0
332    pr-url: https://github.com/nodejs/node/pull/9296
333    description: This method now supports passing `options`,
334                 specifically `options.ttl`.
335-->
336
337* `hostname` {string} Host name to resolve.
338* `options` {Object}
339  * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
340    When `true`, the callback receives an array of
341    `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of
342    strings, with the TTL expressed in seconds.
343* `callback` {Function}
344  * `err` {Error}
345  * `addresses` {string[] | Object[]}
346
347Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the
348`hostname`. The `addresses` argument passed to the `callback` function
349will contain an array of IPv6 addresses.
350
351## `dns.resolveAny(hostname, callback)`
352
353* `hostname` {string}
354* `callback` {Function}
355  * `err` {Error}
356  * `ret` {Object[]}
357
358Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
359The `ret` argument passed to the `callback` function will be an array containing
360various types of records. Each object has a property `type` that indicates the
361type of the current record. And depending on the `type`, additional properties
362will be present on the object:
363
364| Type | Properties |
365|------|------------|
366| `'A'` | `address`/`ttl` |
367| `'AAAA'` | `address`/`ttl` |
368| `'CNAME'` | `value` |
369| `'MX'` | Refer to [`dns.resolveMx()`][] |
370| `'NAPTR'` | Refer to [`dns.resolveNaptr()`][] |
371| `'NS'` | `value` |
372| `'PTR'` | `value` |
373| `'SOA'` | Refer to [`dns.resolveSoa()`][] |
374| `'SRV'` | Refer to [`dns.resolveSrv()`][] |
375| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dns.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` |
376
377Here is an example of the `ret` object passed to the callback:
378
379<!-- eslint-disable semi -->
380```js
381[ { type: 'A', address: '127.0.0.1', ttl: 299 },
382  { type: 'CNAME', value: 'example.com' },
383  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
384  { type: 'NS', value: 'ns1.example.com' },
385  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
386  { type: 'SOA',
387    nsname: 'ns1.example.com',
388    hostmaster: 'admin.example.com',
389    serial: 156696742,
390    refresh: 900,
391    retry: 900,
392    expire: 1800,
393    minttl: 60 } ]
394```
395
396DNS server operators may choose not to respond to `ANY`
397queries. It may be better to call individual methods like [`dns.resolve4()`][],
398[`dns.resolveMx()`][], and so on. For more details, see [RFC 8482][].
399
400## `dns.resolveCname(hostname, callback)`
401<!-- YAML
402added: v0.3.2
403-->
404
405* `hostname` {string}
406* `callback` {Function}
407  * `err` {Error}
408  * `addresses` {string[]}
409
410Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The
411`addresses` argument passed to the `callback` function
412will contain an array of canonical name records available for the `hostname`
413(e.g. `['bar.example.com']`).
414
415## `dns.resolveMx(hostname, callback)`
416<!-- YAML
417added: v0.1.27
418-->
419
420* `hostname` {string}
421* `callback` {Function}
422  * `err` {Error}
423  * `addresses` {Object[]}
424
425Uses the DNS protocol to resolve mail exchange records (`MX` records) for the
426`hostname`. The `addresses` argument passed to the `callback` function will
427contain an array of objects containing both a `priority` and `exchange`
428property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
429
430## `dns.resolveNaptr(hostname, callback)`
431<!-- YAML
432added: v0.9.12
433-->
434
435* `hostname` {string}
436* `callback` {Function}
437  * `err` {Error}
438  * `addresses` {Object[]}
439
440Uses the DNS protocol to resolve regular expression based records (`NAPTR`
441records) for the `hostname`. The `addresses` argument passed to the `callback`
442function will contain an array of objects with the following properties:
443
444* `flags`
445* `service`
446* `regexp`
447* `replacement`
448* `order`
449* `preference`
450
451<!-- eslint-skip -->
452```js
453{
454  flags: 's',
455  service: 'SIP+D2U',
456  regexp: '',
457  replacement: '_sip._udp.example.com',
458  order: 30,
459  preference: 100
460}
461```
462
463## `dns.resolveNs(hostname, callback)`
464<!-- YAML
465added: v0.1.90
466-->
467
468* `hostname` {string}
469* `callback` {Function}
470  * `err` {Error}
471  * `addresses` {string[]}
472
473Uses the DNS protocol to resolve name server records (`NS` records) for the
474`hostname`. The `addresses` argument passed to the `callback` function will
475contain an array of name server records available for `hostname`
476(e.g. `['ns1.example.com', 'ns2.example.com']`).
477
478## `dns.resolvePtr(hostname, callback)`
479<!-- YAML
480added: v6.0.0
481-->
482
483* `hostname` {string}
484* `callback` {Function}
485  * `err` {Error}
486  * `addresses` {string[]}
487
488Uses the DNS protocol to resolve pointer records (`PTR` records) for the
489`hostname`. The `addresses` argument passed to the `callback` function will
490be an array of strings containing the reply records.
491
492## `dns.resolveSoa(hostname, callback)`
493<!-- YAML
494added: v0.11.10
495-->
496
497* `hostname` {string}
498* `callback` {Function}
499  * `err` {Error}
500  * `address` {Object}
501
502Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
503the `hostname`. The `address` argument passed to the `callback` function will
504be an object with the following properties:
505
506* `nsname`
507* `hostmaster`
508* `serial`
509* `refresh`
510* `retry`
511* `expire`
512* `minttl`
513
514<!-- eslint-skip -->
515```js
516{
517  nsname: 'ns.example.com',
518  hostmaster: 'root.example.com',
519  serial: 2013101809,
520  refresh: 10000,
521  retry: 2400,
522  expire: 604800,
523  minttl: 3600
524}
525```
526
527## `dns.resolveSrv(hostname, callback)`
528<!-- YAML
529added: v0.1.27
530-->
531
532* `hostname` {string}
533* `callback` {Function}
534  * `err` {Error}
535  * `addresses` {Object[]}
536
537Uses the DNS protocol to resolve service records (`SRV` records) for the
538`hostname`. The `addresses` argument passed to the `callback` function will
539be an array of objects with the following properties:
540
541* `priority`
542* `weight`
543* `port`
544* `name`
545
546<!-- eslint-skip -->
547```js
548{
549  priority: 10,
550  weight: 5,
551  port: 21223,
552  name: 'service.example.com'
553}
554```
555
556## `dns.resolveTxt(hostname, callback)`
557<!-- YAML
558added: v0.1.27
559-->
560
561* `hostname` {string}
562* `callback` {Function}
563  * `err` {Error}
564  * `records` <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string[][]&gt;</a>
565
566Uses the DNS protocol to resolve text queries (`TXT` records) for the
567`hostname`. The `records` argument passed to the `callback` function is a
568two-dimensional array of the text records available for `hostname` (e.g.
569`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
570one record. Depending on the use case, these could be either joined together or
571treated separately.
572
573## `dns.reverse(ip, callback)`
574<!-- YAML
575added: v0.1.16
576-->
577
578* `ip` {string}
579* `callback` {Function}
580  * `err` {Error}
581  * `hostnames` {string[]}
582
583Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
584array of host names.
585
586On error, `err` is an [`Error`][] object, where `err.code` is
587one of the [DNS error codes][].
588
589## `dns.setServers(servers)`
590<!-- YAML
591added: v0.11.3
592-->
593
594* `servers` {string[]} array of [RFC 5952][] formatted addresses
595
596Sets the IP address and port of servers to be used when performing DNS
597resolution. The `servers` argument is an array of [RFC 5952][] formatted
598addresses. If the port is the IANA default DNS port (53) it can be omitted.
599
600```js
601dns.setServers([
602  '4.4.4.4',
603  '[2001:4860:4860::8888]',
604  '4.4.4.4:1053',
605  '[2001:4860:4860::8888]:1053'
606]);
607```
608
609An error will be thrown if an invalid address is provided.
610
611The `dns.setServers()` method must not be called while a DNS query is in
612progress.
613
614The [`dns.setServers()`][] method affects only [`dns.resolve()`][],
615`dns.resolve*()` and [`dns.reverse()`][] (and specifically *not*
616[`dns.lookup()`][]).
617
618This method works much like
619[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
620That is, if attempting to resolve with the first server provided results in a
621`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with
622subsequent servers provided. Fallback DNS servers will only be used if the
623earlier ones time out or result in some other error.
624
625## DNS promises API
626
627The `dns.promises` API provides an alternative set of asynchronous DNS methods
628that return `Promise` objects rather than using callbacks. The API is accessible
629via `require('dns').promises`.
630
631### Class: `dnsPromises.Resolver`
632<!-- YAML
633added: v10.6.0
634-->
635
636An independent resolver for DNS requests.
637
638Creating a new resolver uses the default server settings. Setting
639the servers used for a resolver using
640[`resolver.setServers()`][`dnsPromises.setServers()`] does not affect
641other resolvers:
642
643```js
644const { Resolver } = require('dns').promises;
645const resolver = new Resolver();
646resolver.setServers(['4.4.4.4']);
647
648// This request will use the server at 4.4.4.4, independent of global settings.
649resolver.resolve4('example.org').then((addresses) => {
650  // ...
651});
652
653// Alternatively, the same code can be written using async-await style.
654(async function() {
655  const addresses = await resolver.resolve4('example.org');
656})();
657```
658
659The following methods from the `dnsPromises` API are available:
660
661* [`resolver.getServers()`][`dnsPromises.getServers()`]
662* [`resolver.resolve()`][`dnsPromises.resolve()`]
663* [`resolver.resolve4()`][`dnsPromises.resolve4()`]
664* [`resolver.resolve6()`][`dnsPromises.resolve6()`]
665* [`resolver.resolveAny()`][`dnsPromises.resolveAny()`]
666* [`resolver.resolveCname()`][`dnsPromises.resolveCname()`]
667* [`resolver.resolveMx()`][`dnsPromises.resolveMx()`]
668* [`resolver.resolveNaptr()`][`dnsPromises.resolveNaptr()`]
669* [`resolver.resolveNs()`][`dnsPromises.resolveNs()`]
670* [`resolver.resolvePtr()`][`dnsPromises.resolvePtr()`]
671* [`resolver.resolveSoa()`][`dnsPromises.resolveSoa()`]
672* [`resolver.resolveSrv()`][`dnsPromises.resolveSrv()`]
673* [`resolver.resolveTxt()`][`dnsPromises.resolveTxt()`]
674* [`resolver.reverse()`][`dnsPromises.reverse()`]
675* [`resolver.setServers()`][`dnsPromises.setServers()`]
676
677### `dnsPromises.getServers()`
678<!-- YAML
679added: v10.6.0
680-->
681
682* Returns: {string[]}
683
684Returns an array of IP address strings, formatted according to [RFC 5952][],
685that are currently configured for DNS resolution. A string will include a port
686section if a custom port is used.
687
688<!-- eslint-disable semi-->
689```js
690[
691  '4.4.4.4',
692  '2001:4860:4860::8888',
693  '4.4.4.4:1053',
694  '[2001:4860:4860::8888]:1053'
695]
696```
697
698### `dnsPromises.lookup(hostname[, options])`
699<!-- YAML
700added: v10.6.0
701-->
702
703* `hostname` {string}
704* `options` {integer | Object}
705  * `family` {integer} The record family. Must be `4`, `6`, or `0`. The value
706    `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:**
707    `0`.
708  * `hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple
709    flags may be passed by bitwise `OR`ing their values.
710  * `all` {boolean} When `true`, the `Promise` is resolved with all addresses in
711    an array. Otherwise, returns a single address. **Default:** `false`.
712  * `verbatim` {boolean} When `true`, the `Promise` is resolved with IPv4 and
713    IPv6 addresses in the order the DNS resolver returned them. When `false`,
714    IPv4 addresses are placed before IPv6 addresses.
715    **Default:** currently `false` (addresses are reordered) but this is
716    expected to change in the not too distant future.
717    New code should use `{ verbatim: true }`.
718
719Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
720AAAA (IPv6) record. All `option` properties are optional. If `options` is an
721integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
722and IPv6 addresses are both returned if found.
723
724With the `all` option set to `true`, the `Promise` is resolved with `addresses`
725being an array of objects with the properties `address` and `family`.
726
727On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
728is the error code.
729Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
730the host name does not exist but also when the lookup fails in other ways
731such as no available file descriptors.
732
733[`dnsPromises.lookup()`][] does not necessarily have anything to do with the DNS
734protocol. The implementation uses an operating system facility that can
735associate names with addresses, and vice versa. This implementation can have
736subtle but important consequences on the behavior of any Node.js program. Please
737take some time to consult the [Implementation considerations section][] before
738using `dnsPromises.lookup()`.
739
740Example usage:
741
742```js
743const dns = require('dns');
744const dnsPromises = dns.promises;
745const options = {
746  family: 6,
747  hints: dns.ADDRCONFIG | dns.V4MAPPED,
748};
749
750dnsPromises.lookup('example.com', options).then((result) => {
751  console.log('address: %j family: IPv%s', result.address, result.family);
752  // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
753});
754
755// When options.all is true, the result will be an Array.
756options.all = true;
757dnsPromises.lookup('example.com', options).then((result) => {
758  console.log('addresses: %j', result);
759  // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
760});
761```
762
763### `dnsPromises.lookupService(address, port)`
764<!-- YAML
765added: v10.6.0
766-->
767
768* `address` {string}
769* `port` {number}
770
771Resolves the given `address` and `port` into a host name and service using
772the operating system's underlying `getnameinfo` implementation.
773
774If `address` is not a valid IP address, a `TypeError` will be thrown.
775The `port` will be coerced to a number. If it is not a legal port, a `TypeError`
776will be thrown.
777
778On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
779is the error code.
780
781```js
782const dnsPromises = require('dns').promises;
783dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
784  console.log(result.hostname, result.service);
785  // Prints: localhost ssh
786});
787```
788
789### `dnsPromises.resolve(hostname[, rrtype])`
790<!-- YAML
791added: v10.6.0
792-->
793
794* `hostname` {string} Host name to resolve.
795* `rrtype` {string} Resource record type. **Default:** `'A'`.
796
797Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
798of the resource records. When successful, the `Promise` is resolved with an
799array of resource records. The type and structure of individual results vary
800based on `rrtype`:
801
802|  `rrtype` | `records` contains             | Result type | Shorthand method         |
803|-----------|--------------------------------|-------------|--------------------------|
804| `'A'`     | IPv4 addresses (default)       | {string}    | [`dnsPromises.resolve4()`][]     |
805| `'AAAA'`  | IPv6 addresses                 | {string}    | [`dnsPromises.resolve6()`][]     |
806| `'ANY'`   | any records                    | {Object}    | [`dnsPromises.resolveAny()`][]   |
807| `'CNAME'` | canonical name records         | {string}    | [`dnsPromises.resolveCname()`][] |
808| `'MX'`    | mail exchange records          | {Object}    | [`dnsPromises.resolveMx()`][]    |
809| `'NAPTR'` | name authority pointer records | {Object}    | [`dnsPromises.resolveNaptr()`][] |
810| `'NS'`    | name server records            | {string}    | [`dnsPromises.resolveNs()`][]    |
811| `'PTR'`   | pointer records                | {string}    | [`dnsPromises.resolvePtr()`][]   |
812| `'SOA'`   | start of authority records     | {Object}    | [`dnsPromises.resolveSoa()`][]   |
813| `'SRV'`   | service records                | {Object}    | [`dnsPromises.resolveSrv()`][]   |
814| `'TXT'`   | text records                   | {string[]}  | [`dnsPromises.resolveTxt()`][]   |
815
816On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
817is one of the [DNS error codes](#dns_error_codes).
818
819### `dnsPromises.resolve4(hostname[, options])`
820<!-- YAML
821added: v10.6.0
822-->
823
824* `hostname` {string} Host name to resolve.
825* `options` {Object}
826  * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
827    When `true`, the `Promise` is resolved with an array of
828    `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings,
829    with the TTL expressed in seconds.
830
831Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the
832`hostname`. On success, the `Promise` is resolved with an array of IPv4
833addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
834
835### `dnsPromises.resolve6(hostname[, options])`
836<!-- YAML
837added: v10.6.0
838-->
839
840* `hostname` {string} Host name to resolve.
841* `options` {Object}
842  * `ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record.
843    When `true`, the `Promise` is resolved with an array of
844    `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of
845    strings, with the TTL expressed in seconds.
846
847Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the
848`hostname`. On success, the `Promise` is resolved with an array of IPv6
849addresses.
850
851### `dnsPromises.resolveAny(hostname)`
852<!-- YAML
853added: v10.6.0
854-->
855
856* `hostname` {string}
857
858Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
859On success, the `Promise` is resolved with an array containing various types of
860records. Each object has a property `type` that indicates the type of the
861current record. And depending on the `type`, additional properties will be
862present on the object:
863
864| Type | Properties |
865|------|------------|
866| `'A'` | `address`/`ttl` |
867| `'AAAA'` | `address`/`ttl` |
868| `'CNAME'` | `value` |
869| `'MX'` | Refer to [`dnsPromises.resolveMx()`][] |
870| `'NAPTR'` | Refer to [`dnsPromises.resolveNaptr()`][] |
871| `'NS'` | `value` |
872| `'PTR'` | `value` |
873| `'SOA'` | Refer to [`dnsPromises.resolveSoa()`][] |
874| `'SRV'` | Refer to [`dnsPromises.resolveSrv()`][] |
875| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` |
876
877Here is an example of the result object:
878
879<!-- eslint-disable semi -->
880```js
881[ { type: 'A', address: '127.0.0.1', ttl: 299 },
882  { type: 'CNAME', value: 'example.com' },
883  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
884  { type: 'NS', value: 'ns1.example.com' },
885  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
886  { type: 'SOA',
887    nsname: 'ns1.example.com',
888    hostmaster: 'admin.example.com',
889    serial: 156696742,
890    refresh: 900,
891    retry: 900,
892    expire: 1800,
893    minttl: 60 } ]
894```
895
896### `dnsPromises.resolveCname(hostname)`
897<!-- YAML
898added: v10.6.0
899-->
900
901* `hostname` {string}
902
903Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
904the `Promise` is resolved with an array of canonical name records available for
905the `hostname` (e.g. `['bar.example.com']`).
906
907### `dnsPromises.resolveMx(hostname)`
908<!-- YAML
909added: v10.6.0
910-->
911
912* `hostname` {string}
913
914Uses the DNS protocol to resolve mail exchange records (`MX` records) for the
915`hostname`. On success, the `Promise` is resolved with an array of objects
916containing both a `priority` and `exchange` property (e.g.
917`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
918
919### `dnsPromises.resolveNaptr(hostname)`
920<!-- YAML
921added: v10.6.0
922-->
923
924* `hostname` {string}
925
926Uses the DNS protocol to resolve regular expression based records (`NAPTR`
927records) for the `hostname`. On success, the `Promise` is resolved with an array
928of objects with the following properties:
929
930* `flags`
931* `service`
932* `regexp`
933* `replacement`
934* `order`
935* `preference`
936
937<!-- eslint-skip -->
938```js
939{
940  flags: 's',
941  service: 'SIP+D2U',
942  regexp: '',
943  replacement: '_sip._udp.example.com',
944  order: 30,
945  preference: 100
946}
947```
948
949### `dnsPromises.resolveNs(hostname)`
950<!-- YAML
951added: v10.6.0
952-->
953
954* `hostname` {string}
955
956Uses the DNS protocol to resolve name server records (`NS` records) for the
957`hostname`. On success, the `Promise` is resolved with an array of name server
958records available for `hostname` (e.g.
959`['ns1.example.com', 'ns2.example.com']`).
960
961### `dnsPromises.resolvePtr(hostname)`
962<!-- YAML
963added: v10.6.0
964-->
965
966* `hostname` {string}
967
968Uses the DNS protocol to resolve pointer records (`PTR` records) for the
969`hostname`. On success, the `Promise` is resolved with an array of strings
970containing the reply records.
971
972### `dnsPromises.resolveSoa(hostname)`
973<!-- YAML
974added: v10.6.0
975-->
976
977* `hostname` {string}
978
979Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
980the `hostname`. On success, the `Promise` is resolved with an object with the
981following properties:
982
983* `nsname`
984* `hostmaster`
985* `serial`
986* `refresh`
987* `retry`
988* `expire`
989* `minttl`
990
991<!-- eslint-skip -->
992```js
993{
994  nsname: 'ns.example.com',
995  hostmaster: 'root.example.com',
996  serial: 2013101809,
997  refresh: 10000,
998  retry: 2400,
999  expire: 604800,
1000  minttl: 3600
1001}
1002```
1003
1004### `dnsPromises.resolveSrv(hostname)`
1005<!-- YAML
1006added: v10.6.0
1007-->
1008
1009* `hostname` {string}
1010
1011Uses the DNS protocol to resolve service records (`SRV` records) for the
1012`hostname`. On success, the `Promise` is resolved with an array of objects with
1013the following properties:
1014
1015* `priority`
1016* `weight`
1017* `port`
1018* `name`
1019
1020<!-- eslint-skip -->
1021```js
1022{
1023  priority: 10,
1024  weight: 5,
1025  port: 21223,
1026  name: 'service.example.com'
1027}
1028```
1029
1030### `dnsPromises.resolveTxt(hostname)`
1031<!-- YAML
1032added: v10.6.0
1033-->
1034
1035* `hostname` {string}
1036
1037Uses the DNS protocol to resolve text queries (`TXT` records) for the
1038`hostname`. On success, the `Promise` is resolved with a two-dimensional array
1039of the text records available for `hostname` (e.g.
1040`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
1041one record. Depending on the use case, these could be either joined together or
1042treated separately.
1043
1044### `dnsPromises.reverse(ip)`
1045<!-- YAML
1046added: v10.6.0
1047-->
1048
1049* `ip` {string}
1050
1051Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
1052array of host names.
1053
1054On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
1055is one of the [DNS error codes](#dns_error_codes).
1056
1057### `dnsPromises.setServers(servers)`
1058<!-- YAML
1059added: v10.6.0
1060-->
1061
1062* `servers` {string[]} array of [RFC 5952][] formatted addresses
1063
1064Sets the IP address and port of servers to be used when performing DNS
1065resolution. The `servers` argument is an array of [RFC 5952][] formatted
1066addresses. If the port is the IANA default DNS port (53) it can be omitted.
1067
1068```js
1069dnsPromises.setServers([
1070  '4.4.4.4',
1071  '[2001:4860:4860::8888]',
1072  '4.4.4.4:1053',
1073  '[2001:4860:4860::8888]:1053'
1074]);
1075```
1076
1077An error will be thrown if an invalid address is provided.
1078
1079The `dnsPromises.setServers()` method must not be called while a DNS query is in
1080progress.
1081
1082This method works much like
1083[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
1084That is, if attempting to resolve with the first server provided results in a
1085`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with
1086subsequent servers provided. Fallback DNS servers will only be used if the
1087earlier ones time out or result in some other error.
1088
1089## Error codes
1090
1091Each DNS query can return one of the following error codes:
1092
1093* `dns.NODATA`: DNS server returned answer with no data.
1094* `dns.FORMERR`: DNS server claims query was misformatted.
1095* `dns.SERVFAIL`: DNS server returned general failure.
1096* `dns.NOTFOUND`: Domain name not found.
1097* `dns.NOTIMP`: DNS server does not implement requested operation.
1098* `dns.REFUSED`: DNS server refused query.
1099* `dns.BADQUERY`: Misformatted DNS query.
1100* `dns.BADNAME`: Misformatted host name.
1101* `dns.BADFAMILY`: Unsupported address family.
1102* `dns.BADRESP`: Misformatted DNS reply.
1103* `dns.CONNREFUSED`: Could not contact DNS servers.
1104* `dns.TIMEOUT`: Timeout while contacting DNS servers.
1105* `dns.EOF`: End of file.
1106* `dns.FILE`: Error reading file.
1107* `dns.NOMEM`: Out of memory.
1108* `dns.DESTRUCTION`: Channel is being destroyed.
1109* `dns.BADSTR`: Misformatted string.
1110* `dns.BADFLAGS`: Illegal flags specified.
1111* `dns.NONAME`: Given host name is not numeric.
1112* `dns.BADHINTS`: Illegal hints flags specified.
1113* `dns.NOTINITIALIZED`: c-ares library initialization not yet performed.
1114* `dns.LOADIPHLPAPI`: Error loading `iphlpapi.dll`.
1115* `dns.ADDRGETNETWORKPARAMS`: Could not find `GetNetworkParams` function.
1116* `dns.CANCELLED`: DNS query cancelled.
1117
1118## Implementation considerations
1119
1120Although [`dns.lookup()`][] and the various `dns.resolve*()/dns.reverse()`
1121functions have the same goal of associating a network name with a network
1122address (or vice versa), their behavior is quite different. These differences
1123can have subtle but significant consequences on the behavior of Node.js
1124programs.
1125
1126### `dns.lookup()`
1127
1128Under the hood, [`dns.lookup()`][] uses the same operating system facilities
1129as most other programs. For instance, [`dns.lookup()`][] will almost always
1130resolve a given name the same way as the `ping` command. On most POSIX-like
1131operating systems, the behavior of the [`dns.lookup()`][] function can be
1132modified by changing settings in nsswitch.conf(5) and/or resolv.conf(5),
1133but changing these files will change the behavior of all other
1134programs running on the same operating system.
1135
1136Though the call to `dns.lookup()` will be asynchronous from JavaScript's
1137perspective, it is implemented as a synchronous call to getaddrinfo(3) that runs
1138on libuv's threadpool. This can have surprising negative performance
1139implications for some applications, see the [`UV_THREADPOOL_SIZE`][]
1140documentation for more information.
1141
1142Various networking APIs will call `dns.lookup()` internally to resolve
1143host names. If that is an issue, consider resolving the host name to an address
1144using `dns.resolve()` and using the address instead of a host name. Also, some
1145networking APIs (such as [`socket.connect()`][] and [`dgram.createSocket()`][])
1146allow the default resolver, `dns.lookup()`, to be replaced.
1147
1148### `dns.resolve()`, `dns.resolve*()` and `dns.reverse()`
1149
1150These functions are implemented quite differently than [`dns.lookup()`][]. They
1151do not use getaddrinfo(3) and they _always_ perform a DNS query on the
1152network. This network communication is always done asynchronously, and does not
1153use libuv's threadpool.
1154
1155As a result, these functions cannot have the same negative impact on other
1156processing that happens on libuv's threadpool that [`dns.lookup()`][] can have.
1157
1158They do not use the same set of configuration files than what [`dns.lookup()`][]
1159uses. For instance, _they do not use the configuration from `/etc/hosts`_.
1160
1161[`Error`]: errors.html#errors_class_error
1162[`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size
1163[`dgram.createSocket()`]: dgram.html#dgram_dgram_createsocket_options_callback
1164[`dns.getServers()`]: #dns_dns_getservers
1165[`dns.lookup()`]: #dns_dns_lookup_hostname_options_callback
1166[`dns.resolve()`]: #dns_dns_resolve_hostname_rrtype_callback
1167[`dns.resolve4()`]: #dns_dns_resolve4_hostname_options_callback
1168[`dns.resolve6()`]: #dns_dns_resolve6_hostname_options_callback
1169[`dns.resolveAny()`]: #dns_dns_resolveany_hostname_callback
1170[`dns.resolveCname()`]: #dns_dns_resolvecname_hostname_callback
1171[`dns.resolveMx()`]: #dns_dns_resolvemx_hostname_callback
1172[`dns.resolveNaptr()`]: #dns_dns_resolvenaptr_hostname_callback
1173[`dns.resolveNs()`]: #dns_dns_resolvens_hostname_callback
1174[`dns.resolvePtr()`]: #dns_dns_resolveptr_hostname_callback
1175[`dns.resolveSoa()`]: #dns_dns_resolvesoa_hostname_callback
1176[`dns.resolveSrv()`]: #dns_dns_resolvesrv_hostname_callback
1177[`dns.resolveTxt()`]: #dns_dns_resolvetxt_hostname_callback
1178[`dns.reverse()`]: #dns_dns_reverse_ip_callback
1179[`dns.setServers()`]: #dns_dns_setservers_servers
1180[`dnsPromises.getServers()`]: #dns_dnspromises_getservers
1181[`dnsPromises.lookup()`]: #dns_dnspromises_lookup_hostname_options
1182[`dnsPromises.resolve()`]: #dns_dnspromises_resolve_hostname_rrtype
1183[`dnsPromises.resolve4()`]: #dns_dnspromises_resolve4_hostname_options
1184[`dnsPromises.resolve6()`]: #dns_dnspromises_resolve6_hostname_options
1185[`dnsPromises.resolveAny()`]: #dns_dnspromises_resolveany_hostname
1186[`dnsPromises.resolveCname()`]: #dns_dnspromises_resolvecname_hostname
1187[`dnsPromises.resolveMx()`]: #dns_dnspromises_resolvemx_hostname
1188[`dnsPromises.resolveNaptr()`]: #dns_dnspromises_resolvenaptr_hostname
1189[`dnsPromises.resolveNs()`]: #dns_dnspromises_resolvens_hostname
1190[`dnsPromises.resolvePtr()`]: #dns_dnspromises_resolveptr_hostname
1191[`dnsPromises.resolveSoa()`]: #dns_dnspromises_resolvesoa_hostname
1192[`dnsPromises.resolveSrv()`]: #dns_dnspromises_resolvesrv_hostname
1193[`dnsPromises.resolveTxt()`]: #dns_dnspromises_resolvetxt_hostname
1194[`dnsPromises.reverse()`]: #dns_dnspromises_reverse_ip
1195[`dnsPromises.setServers()`]: #dns_dnspromises_setservers_servers
1196[`socket.connect()`]: net.html#net_socket_connect_options_connectlistener
1197[`util.promisify()`]: util.html#util_util_promisify_original
1198[DNS error codes]: #dns_error_codes
1199[Domain Name System (DNS)]: https://en.wikipedia.org/wiki/Domain_Name_System
1200[Implementation considerations section]: #dns_implementation_considerations
1201[RFC 5952]: https://tools.ietf.org/html/rfc5952#section-6
1202[RFC 8482]: https://tools.ietf.org/html/rfc8482
1203[supported `getaddrinfo` flags]: #dns_supported_getaddrinfo_flags
1204