86bee21648768304b43c328d088bc964952a8245
[platform/upstream/nodejs.git] / doc / api / dns.markdown
1 # DNS
2
3     Stability: 2 - Stable
4
5 The `dns` module contains functions belonging to two different categories:
6
7 1) Functions that use the underlying operating system facilities to perform
8 name resolution, and that do not necessarily perform any network communication.
9 This category contains only one function: [`dns.lookup()`][]. __Developers
10 looking to perform name resolution in the same way that other applications on
11 the same operating system behave should use [`dns.lookup()`][].__
12
13 For example, looking up `nodejs.org`.
14
15     const dns = require('dns');
16
17     dns.lookup('nodejs.org', (err, addresses, family) => {
18       console.log('addresses:', addresses);
19     });
20
21 2) Functions that connect to an actual DNS server to perform name resolution,
22 and that _always_ use the network to perform DNS queries. This category
23 contains all functions in the `dns` module _except_ [`dns.lookup()`][]. These
24 functions do not use the same set of configuration files used by
25 [`dns.lookup()`][] (e.g. `/etc/hosts`). These functions should be used by
26 developers who do not want to use the underlying operating system's facilities
27 for name resolution, and instead want to _always_ perform DNS queries.
28
29 Below is an example that resolves `'nodejs.org'` then reverse resolves the IP
30 addresses that are returned.
31
32     const dns = require('dns');
33
34     dns.resolve4('nodejs.org', (err, addresses) => {
35       if (err) throw err;
36
37       console.log(`addresses: ${JSON.stringify(addresses)}`);
38
39       addresses.forEach((a) => {
40         dns.reverse(a, (err, hostnames) => {
41           if (err) {
42             throw err;
43           }
44           console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
45         });
46       });
47     });
48
49 There are subtle consequences in choosing one over the other, please consult
50 the [Implementation considerations section][] for more information.
51
52 ## dns.getServers()
53
54 Returns an array of IP address strings that are being used for name
55 resolution.
56
57 ## dns.lookup(hostname[, options], callback)
58
59 Resolves a hostname (e.g. `'nodejs.org'`) into the first found A (IPv4) or
60 AAAA (IPv6) record. `options` can be an object or integer. If `options` is
61 not provided, then IPv4 and IPv6 addresses are both valid. If `options` is
62 an integer, then it must be `4` or `6`.
63
64 Alternatively, `options` can be an object containing these properties:
65
66 * `family` {Number} - The record family. If present, must be the integer
67   `4` or `6`. If not provided, both IP v4 and v6 addresses are accepted.
68 * `hints`: {Number} - If present, it should be one or more of the supported
69   `getaddrinfo` flags. If `hints` is not provided, then no flags are passed to
70   `getaddrinfo`. Multiple flags can be passed through `hints` by logically
71   `OR`ing their values.
72   See [supported `getaddrinfo` flags][] below for more information on supported
73   flags.
74 * `all`: {Boolean} - When `true`, the callback returns all resolved addresses
75   in an array, otherwise returns a single address. Defaults to `false`.
76
77 All properties are optional. An example usage of options is shown below.
78
79     {
80       family: 4,
81       hints: dns.ADDRCONFIG | dns.V4MAPPED,
82       all: false
83     }
84
85 The `callback` function has arguments `(err, address, family)`. `address` is a
86 string representation of an IPv4 or IPv6 address. `family` is either the
87 integer `4` or `6` and denotes the family of `address` (not necessarily the
88 value initially passed to `lookup`).
89
90 With the `all` option set to `true`, the arguments change to
91 `(err, addresses)`, with `addresses` being an array of objects with the
92 properties `address` and `family`.
93
94 On error, `err` is an [`Error`][] object, where `err.code` is the error code.
95 Keep in mind that `err.code` will be set to `'ENOENT'` not only when
96 the hostname does not exist but also when the lookup fails in other ways
97 such as no available file descriptors.
98
99 `dns.lookup()` does not necessarily have anything to do with the DNS protocol.
100 The implementation uses an operating system facility that can associate names
101 with addresses, and vice versa. This implementation can have subtle but
102 important consequences on the behavior of any Node.js program. Please take some
103 time to consult the [Implementation considerations section][] before using
104 `dns.lookup()`.
105
106 ### Supported getaddrinfo flags
107
108 The following flags can be passed as hints to [`dns.lookup()`][].
109
110 - `dns.ADDRCONFIG`: Returned address types are determined by the types
111 of addresses supported by the current system. For example, IPv4 addresses
112 are only returned if the current system has at least one IPv4 address
113 configured. Loopback addresses are not considered.
114 - `dns.V4MAPPED`: If the IPv6 family was specified, but no IPv6 addresses were
115 found, then return IPv4 mapped IPv6 addresses. Note that it is not supported
116 on some operating systems (e.g FreeBSD 10.1).
117
118 ## dns.lookupService(address, port, callback)
119
120 Resolves the given `address` and `port` into a hostname and service using
121 the operating system's underlying `getnameinfo` implementation.
122
123 The callback has arguments `(err, hostname, service)`. The `hostname` and
124 `service` arguments are strings (e.g. `'localhost'` and `'http'` respectively).
125
126 On error, `err` is an [`Error`][] object, where `err.code` is the error code.
127
128     const dns = require('dns');
129     dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
130       console.log(hostname, service);
131         // Prints: localhost ssh
132     });
133
134 ## dns.resolve(hostname[, rrtype], callback)
135
136 Uses the DNS protocol to resolve a hostname (e.g. `'nodejs.org'`) into an
137 array of the record types specified by `rrtype`.
138
139 Valid values for `rrtype` are:
140
141  * `'A'` - IPV4 addresses, default
142  * `'AAAA'` - IPV6 addresses
143  * `'MX'` - mail exchange records
144  * `'TXT'` - text records
145  * `'SRV'` - SRV records
146  * `'PTR'` - used for reverse IP lookups
147  * `'NS'` - name server records
148  * `'CNAME'` - canonical name records
149  * `'SOA'` - start of authority record
150
151 The `callback` function has arguments `(err, addresses)`. When successful,
152 `addresses` will be an array. The type of each  item in `addresses` is
153 determined by the record type, and described in the documentation for the
154 corresponding lookup methods below.
155
156 On error, `err` is an [`Error`][] object, where `err.code` is
157 one of the error codes listed below.
158
159 ## dns.resolve4(hostname, callback)
160
161 Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the
162 `hostname`. The `addresses` argument passed to the `callback` function
163 will contain an array of IPv4 addresses (e.g.
164 `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
165
166 ## dns.resolve6(hostname, callback)
167
168 Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the
169 `hostname`. The `addresses` argument passed to the `callback` function
170 will contain an array of IPv6 addresses.
171
172 ## dns.resolveCname(hostname, callback)
173
174 Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The
175 `addresses` argument passed to the `callback` function
176 will contain an of canonical name records available for the `hostname`
177 (e.g. `['bar.example.com']`).
178
179 ## dns.resolveMx(hostname, callback)
180
181 Uses the DNS protocol to resolve mail exchange records (`MX` records) for the
182 `hostname`. The `addresses` argument passed to the `callback` function will
183 contain an array of objects containing both a `priority` and `exchange`
184 property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
185
186 ## dns.resolveNs(hostname, callback)
187
188 Uses the DNS protocol to resolve name server records (`NS` records) for the
189 `hostname`. The `addresses` argument passed to the `callback` function will
190 contain an array of name server records available for `hostname`
191 (e.g., `['ns1.example.com', 'ns2.example.com']`).
192
193 ## dns.resolveSoa(hostname, callback)
194
195 Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
196 the `hostname`. The `addresses` argument passed to the `callback` function will
197 be an object with the following properties:
198
199 * `nsname`
200 * `hostmaster`
201 * `serial`
202 * `refresh`
203 * `retry`
204 * `expire`
205 * `minttl`
206
207     {
208       nsname: 'ns.example.com',
209       hostmaster: 'root.example.com',
210       serial: 2013101809,
211       refresh: 10000,
212       retry: 2400,
213       expire: 604800,
214       minttl: 3600
215     }
216
217 ## dns.resolveSrv(hostname, callback)
218
219 Uses the DNS protocol to resolve service records (`SRV` records) for the
220 `hostname`. The `addresses` argument passed to the `callback` function will
221 be an array of objects with the following properties:
222
223 * `priority`
224 * `weight`
225 * `port`
226 * `name`
227
228     {
229       priority: 10,
230       weight: 5,
231       port: 21223,
232       name: 'service.example.com'
233     }
234
235 ## dns.resolveTxt(hostname, callback)
236
237 Uses the DNS protocol to resolve text queries (`TXT` records) for the
238 `hostname`. The `addresses` argument passed to the `callback` function is
239 is a two-dimentional array of the text records available for `hostname` (e.g.,
240 `[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
241 one record. Depending on the use case, these could be either joined together or
242 treated separately.
243
244 ## dns.reverse(ip, callback)
245
246 Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
247 array of hostnames.
248
249 The `callback` function has arguments `(err, hostnames)`, where `hostnames`
250 is an array of resolved hostnames for the given `ip`.
251
252 On error, `err` is an [`Error`][] object, where `err.code` is
253 one of the error codes listed below.
254
255 ## dns.setServers(servers)
256
257 Sets the IP addresses of the servers to be used when resolving. The `servers`
258 argument is an array of IPv4 or IPv6 addresses.
259
260 If a port specified on the address it will be removed.
261
262 An error will be thrown if an invalid address is provided.
263
264 The `dns.setServers()` method must not be called while a DNS query is in
265 progress.
266
267 ## Error codes
268
269 Each DNS query can return one of the following error codes:
270
271 - `dns.NODATA`: DNS server returned answer with no data.
272 - `dns.FORMERR`: DNS server claims query was misformatted.
273 - `dns.SERVFAIL`: DNS server returned general failure.
274 - `dns.NOTFOUND`: Domain name not found.
275 - `dns.NOTIMP`: DNS server does not implement requested operation.
276 - `dns.REFUSED`: DNS server refused query.
277 - `dns.BADQUERY`: Misformatted DNS query.
278 - `dns.BADNAME`: Misformatted hostname.
279 - `dns.BADFAMILY`: Unsupported address family.
280 - `dns.BADRESP`: Misformatted DNS reply.
281 - `dns.CONNREFUSED`: Could not contact DNS servers.
282 - `dns.TIMEOUT`: Timeout while contacting DNS servers.
283 - `dns.EOF`: End of file.
284 - `dns.FILE`: Error reading file.
285 - `dns.NOMEM`: Out of memory.
286 - `dns.DESTRUCTION`: Channel is being destroyed.
287 - `dns.BADSTR`: Misformatted string.
288 - `dns.BADFLAGS`: Illegal flags specified.
289 - `dns.NONAME`: Given hostname is not numeric.
290 - `dns.BADHINTS`: Illegal hints flags specified.
291 - `dns.NOTINITIALIZED`: c-ares library initialization not yet performed.
292 - `dns.LOADIPHLPAPI`: Error loading iphlpapi.dll.
293 - `dns.ADDRGETNETWORKPARAMS`: Could not find GetNetworkParams function.
294 - `dns.CANCELLED`: DNS query cancelled.
295
296 ## Implementation considerations
297
298 Although [`dns.lookup()`][] and the various `dns.resolve*()/dns.reverse()`
299 functions have the same goal of associating a network name with a network
300 address (or vice versa), their behavior is quite different. These differences
301 can have subtle but significant consequences on the behavior of Node.js
302 programs.
303
304 ### `dns.lookup()`
305
306 Under the hood, [`dns.lookup()`][] uses the same operating system facilities
307 as most other programs. For instance, [`dns.lookup()`][] will almost always
308 resolve a given name the same way as the `ping` command. On most POSIX-like
309 operating systems, the behavior of the [`dns.lookup()`][] function can be
310 modified by changing settings in `nsswitch.conf(5)` and/or `resolv.conf(5)`,
311 but note that changing these files will change the behavior of _all other
312 programs running on the same operating system_.
313
314 Though the call to `dns.lookup()` will be asynchronous from JavaScript's
315 perspective, it is implemented as a synchronous call to `getaddrinfo(3)` that
316 runs on libuv's threadpool. Because libuv's threadpool has a fixed size, it
317 means that if for whatever reason the call to `getaddrinfo(3)` takes a long
318 time, other operations that could run on libuv's threadpool (such as filesystem
319 operations) will experience degraded performance. In order to mitigate this
320 issue, one potential solution is to increase the size of libuv's threadpool by
321 setting the `'UV_THREADPOOL_SIZE'` environment variable to a value greater than
322 `4` (its current default value). For more information on libuv's threadpool, see
323 [the official libuv documentation][].
324
325 ### `dns.resolve()`, `dns.resolve*()` and `dns.reverse()`
326
327 These functions are implemented quite differently than [`dns.lookup()`][]. They
328 do not use `getaddrinfo(3)` and they _always_ perform a DNS query on the
329 network. This network communication is always done asynchronously, and does not
330 use libuv's threadpool.
331
332 As a result, these functions cannot have the same negative impact on other
333 processing that happens on libuv's threadpool that [`dns.lookup()`][] can have.
334
335 They do not use the same set of configuration files than what [`dns.lookup()`][]
336 uses. For instance, _they do not use the configuration from `/etc/hosts`_.
337
338 [`dns.lookup()`]: #dns_dns_lookup_hostname_options_callback
339 [`dns.resolve()`]: #dns_dns_resolve_hostname_rrtype_callback
340 [`dns.resolve4()`]: #dns_dns_resolve4_hostname_callback
341 [`Error`]: errors.html#errors_class_error
342 [Implementation considerations section]: #dns_implementation_considerations
343 [supported `getaddrinfo` flags]: #dns_supported_getaddrinfo_flags
344 [the official libuv documentation]: http://docs.libuv.org/en/latest/threadpool.html