• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UDP/datagram sockets
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- name=dgram -->
8
9<!-- source_link=lib/dgram.js -->
10
11The `dgram` module provides an implementation of UDP datagram sockets.
12
13```js
14const dgram = require('dgram');
15const server = dgram.createSocket('udp4');
16
17server.on('error', (err) => {
18  console.log(`server error:\n${err.stack}`);
19  server.close();
20});
21
22server.on('message', (msg, rinfo) => {
23  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
24});
25
26server.on('listening', () => {
27  const address = server.address();
28  console.log(`server listening ${address.address}:${address.port}`);
29});
30
31server.bind(41234);
32// Prints: server listening 0.0.0.0:41234
33```
34
35## Class: `dgram.Socket`
36<!-- YAML
37added: v0.1.99
38-->
39
40* Extends: {EventEmitter}
41
42Encapsulates the datagram functionality.
43
44New instances of `dgram.Socket` are created using [`dgram.createSocket()`][].
45The `new` keyword is not to be used to create `dgram.Socket` instances.
46
47### Event: `'close'`
48<!-- YAML
49added: v0.1.99
50-->
51
52The `'close'` event is emitted after a socket is closed with [`close()`][].
53Once triggered, no new `'message'` events will be emitted on this socket.
54
55### Event: `'connect'`
56<!-- YAML
57added: v12.0.0
58-->
59
60The `'connect'` event is emitted after a socket is associated to a remote
61address as a result of a successful [`connect()`][] call.
62
63### Event: `'error'`
64<!-- YAML
65added: v0.1.99
66-->
67
68* `exception` {Error}
69
70The `'error'` event is emitted whenever any error occurs. The event handler
71function is passed a single `Error` object.
72
73### Event: `'listening'`
74<!-- YAML
75added: v0.1.99
76-->
77
78The `'listening'` event is emitted once the `dgram.Socket` is addressable and
79can receive data. This happens either explicitly with `socket.bind()` or
80implicitly the first time data is sent using `socket.send()`.
81Until the `dgram.Socket` is listening, the underlying system resources do not
82exist and calls such as `socket.address()` and `socket.setTTL()` will fail.
83
84### Event: `'message'`
85<!-- YAML
86added: v0.1.99
87-->
88
89The `'message'` event is emitted when a new datagram is available on a socket.
90The event handler function is passed two arguments: `msg` and `rinfo`.
91
92* `msg` {Buffer} The message.
93* `rinfo` {Object} Remote address information.
94  * `address` {string} The sender address.
95  * `family` {string} The address family (`'IPv4'` or `'IPv6'`).
96  * `port` {number} The sender port.
97  * `size` {number} The message size.
98
99If the source address of the incoming packet is an IPv6 link-local
100address, the interface name is added to the `address`. For
101example, a packet received on the `en0` interface might have the
102address field set to `'fe80::2618:1234:ab11:3b9c%en0'`, where `'%en0'`
103is the interface name as a zone ID suffix.
104
105### `socket.addMembership(multicastAddress[, multicastInterface])`
106<!-- YAML
107added: v0.6.9
108-->
109
110* `multicastAddress` {string}
111* `multicastInterface` {string}
112
113Tells the kernel to join a multicast group at the given `multicastAddress` and
114`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the
115`multicastInterface` argument is not specified, the operating system will choose
116one interface and will add membership to it. To add membership to every
117available interface, call `addMembership` multiple times, once per interface.
118
119When called on an unbound socket, this method will implicitly bind to a random
120port, listening on all interfaces.
121
122When sharing a UDP socket across multiple `cluster` workers, the
123`socket.addMembership()` function must be called only once or an
124`EADDRINUSE` error will occur:
125
126```js
127const cluster = require('cluster');
128const dgram = require('dgram');
129if (cluster.isMaster) {
130  cluster.fork(); // Works ok.
131  cluster.fork(); // Fails with EADDRINUSE.
132} else {
133  const s = dgram.createSocket('udp4');
134  s.bind(1234, () => {
135    s.addMembership('224.0.0.114');
136  });
137}
138```
139
140### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
141<!-- YAML
142added: v12.16.0
143-->
144* `sourceAddress` {string}
145* `groupAddress` {string}
146* `multicastInterface` {string}
147
148Tells the kernel to join a source-specific multicast channel at the given
149`sourceAddress` and `groupAddress`, using the `multicastInterface` with the
150`IP_ADD_SOURCE_MEMBERSHIP` socket option. If the `multicastInterface` argument
151is not specified, the operating system will choose one interface and will add
152membership to it. To add membership to every available interface, call
153`socket.addSourceSpecificMembership()` multiple times, once per interface.
154
155When called on an unbound socket, this method will implicitly bind to a random
156port, listening on all interfaces.
157
158### `socket.address()`
159<!-- YAML
160added: v0.1.99
161-->
162
163* Returns: {Object}
164
165Returns an object containing the address information for a socket.
166For UDP sockets, this object will contain `address`, `family` and `port`
167properties.
168
169This method throws `EBADF` if called on an unbound socket.
170
171### `socket.bind([port][, address][, callback])`
172<!-- YAML
173added: v0.1.99
174changes:
175  - version: v0.10
176    description: The method was changed to an asynchronous execution model.
177                 Legacy code would need to be changed to pass a callback
178                 function to the method call.
179-->
180
181* `port` {integer}
182* `address` {string}
183* `callback` {Function} with no parameters. Called when binding is complete.
184
185For UDP sockets, causes the `dgram.Socket` to listen for datagram
186messages on a named `port` and optional `address`. If `port` is not
187specified or is `0`, the operating system will attempt to bind to a
188random port. If `address` is not specified, the operating system will
189attempt to listen on all addresses. Once binding is complete, a
190`'listening'` event is emitted and the optional `callback` function is
191called.
192
193Specifying both a `'listening'` event listener and passing a
194`callback` to the `socket.bind()` method is not harmful but not very
195useful.
196
197A bound datagram socket keeps the Node.js process running to receive
198datagram messages.
199
200If binding fails, an `'error'` event is generated. In rare case (e.g.
201attempting to bind with a closed socket), an [`Error`][] may be thrown.
202
203Example of a UDP server listening on port 41234:
204
205```js
206const dgram = require('dgram');
207const server = dgram.createSocket('udp4');
208
209server.on('error', (err) => {
210  console.log(`server error:\n${err.stack}`);
211  server.close();
212});
213
214server.on('message', (msg, rinfo) => {
215  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
216});
217
218server.on('listening', () => {
219  const address = server.address();
220  console.log(`server listening ${address.address}:${address.port}`);
221});
222
223server.bind(41234);
224// Prints: server listening 0.0.0.0:41234
225```
226
227### `socket.bind(options[, callback])`
228<!-- YAML
229added: v0.11.14
230-->
231
232* `options` {Object} Required. Supports the following properties:
233  * `port` {integer}
234  * `address` {string}
235  * `exclusive` {boolean}
236  * `fd` {integer}
237* `callback` {Function}
238
239For UDP sockets, causes the `dgram.Socket` to listen for datagram
240messages on a named `port` and optional `address` that are passed as
241properties of an `options` object passed as the first argument. If
242`port` is not specified or is `0`, the operating system will attempt
243to bind to a random port. If `address` is not specified, the operating
244system will attempt to listen on all addresses. Once binding is
245complete, a `'listening'` event is emitted and the optional `callback`
246function is called.
247
248The `options` object may contain a `fd` property. When a `fd` greater
249than `0` is set, it will wrap around an existing socket with the given
250file descriptor. In this case, the properties of `port` and `address`
251will be ignored.
252
253Specifying both a `'listening'` event listener and passing a
254`callback` to the `socket.bind()` method is not harmful but not very
255useful.
256
257The `options` object may contain an additional `exclusive` property that is
258used when using `dgram.Socket` objects with the [`cluster`][] module. When
259`exclusive` is set to `false` (the default), cluster workers will use the same
260underlying socket handle allowing connection handling duties to be shared.
261When `exclusive` is `true`, however, the handle is not shared and attempted
262port sharing results in an error.
263
264A bound datagram socket keeps the Node.js process running to receive
265datagram messages.
266
267If binding fails, an `'error'` event is generated. In rare case (e.g.
268attempting to bind with a closed socket), an [`Error`][] may be thrown.
269
270An example socket listening on an exclusive port is shown below.
271
272```js
273socket.bind({
274  address: 'localhost',
275  port: 8000,
276  exclusive: true
277});
278```
279
280### `socket.close([callback])`
281<!-- YAML
282added: v0.1.99
283-->
284
285* `callback` {Function} Called when the socket has been closed.
286
287Close the underlying socket and stop listening for data on it. If a callback is
288provided, it is added as a listener for the [`'close'`][] event.
289
290### `socket.connect(port[, address][, callback])`
291<!-- YAML
292added: v12.0.0
293-->
294
295* `port` {integer}
296* `address` {string}
297* `callback` {Function} Called when the connection is completed or on error.
298
299Associates the `dgram.Socket` to a remote address and port. Every
300message sent by this handle is automatically sent to that destination. Also,
301the socket will only receive messages from that remote peer.
302Trying to call `connect()` on an already connected socket will result
303in an [`ERR_SOCKET_DGRAM_IS_CONNECTED`][] exception. If `address` is not
304provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets)
305will be used by default. Once the connection is complete, a `'connect'` event
306is emitted and the optional `callback` function is called. In case of failure,
307the `callback` is called or, failing this, an `'error'` event is emitted.
308
309### `socket.disconnect()`
310<!-- YAML
311added: v12.0.0
312-->
313
314A synchronous function that disassociates a connected `dgram.Socket` from
315its remote address. Trying to call `disconnect()` on an unbound or already
316disconnected socket will result in an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][]
317exception.
318
319### `socket.dropMembership(multicastAddress[, multicastInterface])`
320<!-- YAML
321added: v0.6.9
322-->
323
324* `multicastAddress` {string}
325* `multicastInterface` {string}
326
327Instructs the kernel to leave a multicast group at `multicastAddress` using the
328`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
329kernel when the socket is closed or the process terminates, so most apps will
330never have reason to call this.
331
332If `multicastInterface` is not specified, the operating system will attempt to
333drop membership on all valid interfaces.
334
335### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
336<!-- YAML
337added: v12.16.0
338-->
339
340* `sourceAddress` {string}
341* `groupAddress` {string}
342* `multicastInterface` {string}
343
344Instructs the kernel to leave a source-specific multicast channel at the given
345`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`
346socket option. This method is automatically called by the kernel when the
347socket is closed or the process terminates, so most apps will never have
348reason to call this.
349
350If `multicastInterface` is not specified, the operating system will attempt to
351drop membership on all valid interfaces.
352
353### `socket.getRecvBufferSize()`
354<!-- YAML
355added: v8.7.0
356-->
357
358* Returns: {number} the `SO_RCVBUF` socket receive buffer size in bytes.
359
360This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
361
362### `socket.getSendBufferSize()`
363<!-- YAML
364added: v8.7.0
365-->
366
367* Returns: {number} the `SO_SNDBUF` socket send buffer size in bytes.
368
369This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
370
371### `socket.ref()`
372<!-- YAML
373added: v0.9.1
374-->
375
376* Returns: {dgram.Socket}
377
378By default, binding a socket will cause it to block the Node.js process from
379exiting as long as the socket is open. The `socket.unref()` method can be used
380to exclude the socket from the reference counting that keeps the Node.js
381process active. The `socket.ref()` method adds the socket back to the reference
382counting and restores the default behavior.
383
384Calling `socket.ref()` multiples times will have no additional effect.
385
386The `socket.ref()` method returns a reference to the socket so calls can be
387chained.
388
389### `socket.remoteAddress()`
390<!-- YAML
391added: v12.0.0
392-->
393
394* Returns: {Object}
395
396Returns an object containing the `address`, `family`, and `port` of the remote
397endpoint. This method throws an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception
398if the socket is not connected.
399
400### `socket.send(msg[, offset, length][, port][, address][, callback])`
401<!-- YAML
402added: v0.1.99
403changes:
404  - version: v12.19.0
405    pr-url: https://github.com/nodejs/node/pull/22413
406    description: The `msg` parameter can now be any `TypedArray` or `DataView`.
407  - version: v8.0.0
408    pr-url: https://github.com/nodejs/node/pull/11985
409    description: The `msg` parameter can be an `Uint8Array` now.
410  - version: v8.0.0
411    pr-url: https://github.com/nodejs/node/pull/10473
412    description: The `address` parameter is always optional now.
413  - version: v6.0.0
414    pr-url: https://github.com/nodejs/node/pull/5929
415    description: On success, `callback` will now be called with an `error`
416                 argument of `null` rather than `0`.
417  - version: v5.7.0
418    pr-url: https://github.com/nodejs/node/pull/4374
419    description: The `msg` parameter can be an array now. Also, the `offset`
420                 and `length` parameters are optional now.
421  - version: v12.0.0
422    pr-url: https://github.com/nodejs/node/pull/26871
423    description: Added support for sending data on connected sockets.
424-->
425
426* `msg` {Buffer|TypedArray|DataView|string|Array} Message to be sent.
427* `offset` {integer} Offset in the buffer where the message starts.
428* `length` {integer} Number of bytes in the message.
429* `port` {integer} Destination port.
430* `address` {string} Destination host name or IP address.
431* `callback` {Function} Called when the message has been sent.
432
433Broadcasts a datagram on the socket.
434For connectionless sockets, the destination `port` and `address` must be
435specified. Connected sockets, on the other hand, will use their associated
436remote endpoint, so the `port` and `address` arguments must not be set.
437
438The `msg` argument contains the message to be sent.
439Depending on its type, different behavior can apply. If `msg` is a `Buffer`,
440any `TypedArray` or a `DataView`,
441the `offset` and `length` specify the offset within the `Buffer` where the
442message begins and the number of bytes in the message, respectively.
443If `msg` is a `String`, then it is automatically converted to a `Buffer`
444with `'utf8'` encoding. With messages that
445contain multi-byte characters, `offset` and `length` will be calculated with
446respect to [byte length][] and not the character position.
447If `msg` is an array, `offset` and `length` must not be specified.
448
449The `address` argument is a string. If the value of `address` is a host name,
450DNS will be used to resolve the address of the host. If `address` is not
451provided or otherwise falsy, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`
452(for `udp6` sockets) will be used by default.
453
454If the socket has not been previously bound with a call to `bind`, the socket
455is assigned a random port number and is bound to the "all interfaces" address
456(`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
457
458An optional `callback` function may be specified to as a way of reporting
459DNS errors or for determining when it is safe to reuse the `buf` object.
460DNS lookups delay the time to send for at least one tick of the
461Node.js event loop.
462
463The only way to know for sure that the datagram has been sent is by using a
464`callback`. If an error occurs and a `callback` is given, the error will be
465passed as the first argument to the `callback`. If a `callback` is not given,
466the error is emitted as an `'error'` event on the `socket` object.
467
468Offset and length are optional but both *must* be set if either are used.
469They are supported only when the first argument is a `Buffer`, a `TypedArray`,
470or a `DataView`.
471
472This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket.
473
474Example of sending a UDP packet to a port on `localhost`;
475
476```js
477const dgram = require('dgram');
478const message = Buffer.from('Some bytes');
479const client = dgram.createSocket('udp4');
480client.send(message, 41234, 'localhost', (err) => {
481  client.close();
482});
483```
484
485Example of sending a UDP packet composed of multiple buffers to a port on
486`127.0.0.1`;
487
488```js
489const dgram = require('dgram');
490const buf1 = Buffer.from('Some ');
491const buf2 = Buffer.from('bytes');
492const client = dgram.createSocket('udp4');
493client.send([buf1, buf2], 41234, (err) => {
494  client.close();
495});
496```
497
498Sending multiple buffers might be faster or slower depending on the
499application and operating system. Run benchmarks to
500determine the optimal strategy on a case-by-case basis. Generally speaking,
501however, sending multiple buffers is faster.
502
503Example of sending a UDP packet using a socket connected to a port on
504`localhost`:
505
506```js
507const dgram = require('dgram');
508const message = Buffer.from('Some bytes');
509const client = dgram.createSocket('udp4');
510client.connect(41234, 'localhost', (err) => {
511  client.send(message, (err) => {
512    client.close();
513  });
514});
515```
516
517#### Note about UDP datagram size
518
519The maximum size of an IPv4/v6 datagram depends on the `MTU`
520(Maximum Transmission Unit) and on the `Payload Length` field size.
521
522* The `Payload Length` field is 16 bits wide, which means that a normal
523  payload cannot exceed 64K octets including the internet header and data
524  (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
525  this is generally true for loopback interfaces, but such long datagram
526  messages are impractical for most hosts and networks.
527
528* The `MTU` is the largest size a given link layer technology can support for
529  datagram messages. For any link, IPv4 mandates a minimum `MTU` of 68
530  octets, while the recommended `MTU` for IPv4 is 576 (typically recommended
531  as the `MTU` for dial-up type applications), whether they arrive whole or in
532  fragments.
533
534  For IPv6, the minimum `MTU` is 1280 octets. However, the mandatory minimum
535  fragment reassembly buffer size is 1500 octets. The value of 68 octets is
536  very small, since most current link layer technologies, like Ethernet, have a
537  minimum `MTU` of 1500.
538
539It is impossible to know in advance the MTU of each link through which
540a packet might travel. Sending a datagram greater than the receiver `MTU` will
541not work because the packet will get silently dropped without informing the
542source that the data did not reach its intended recipient.
543
544### `socket.setBroadcast(flag)`
545<!-- YAML
546added: v0.6.9
547-->
548
549* `flag` {boolean}
550
551Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
552packets may be sent to a local interface's broadcast address.
553
554This method throws `EBADF` if called on an unbound socket.
555
556### `socket.setMulticastInterface(multicastInterface)`
557<!-- YAML
558added: v8.6.0
559-->
560
561* `multicastInterface` {string}
562
563*All references to scope in this section are referring to
564[IPv6 Zone Indices][], which are defined by [RFC 4007][]. In string form, an IP
565with a scope index is written as `'IP%scope'` where scope is an interface name
566or interface number.*
567
568Sets the default outgoing multicast interface of the socket to a chosen
569interface or back to system interface selection. The `multicastInterface` must
570be a valid string representation of an IP from the socket's family.
571
572For IPv4 sockets, this should be the IP configured for the desired physical
573interface. All packets sent to multicast on the socket will be sent on the
574interface determined by the most recent successful use of this call.
575
576For IPv6 sockets, `multicastInterface` should include a scope to indicate the
577interface as in the examples that follow. In IPv6, individual `send` calls can
578also use explicit scope in addresses, so only packets sent to a multicast
579address without specifying an explicit scope are affected by the most recent
580successful use of this call.
581
582This method throws `EBADF` if called on an unbound socket.
583
584#### Example: IPv6 outgoing multicast interface
585
586On most systems, where scope format uses the interface name:
587
588```js
589const socket = dgram.createSocket('udp6');
590
591socket.bind(1234, () => {
592  socket.setMulticastInterface('::%eth1');
593});
594```
595
596On Windows, where scope format uses an interface number:
597
598```js
599const socket = dgram.createSocket('udp6');
600
601socket.bind(1234, () => {
602  socket.setMulticastInterface('::%2');
603});
604```
605
606#### Example: IPv4 outgoing multicast interface
607All systems use an IP of the host on the desired physical interface:
608
609```js
610const socket = dgram.createSocket('udp4');
611
612socket.bind(1234, () => {
613  socket.setMulticastInterface('10.0.0.2');
614});
615```
616
617#### Call results
618
619A call on a socket that is not ready to send or no longer open may throw a *Not
620running* [`Error`][].
621
622If `multicastInterface` can not be parsed into an IP then an *EINVAL*
623[`System Error`][] is thrown.
624
625On IPv4, if `multicastInterface` is a valid address but does not match any
626interface, or if the address does not match the family then
627a [`System Error`][] such as `EADDRNOTAVAIL` or `EPROTONOSUP` is thrown.
628
629On IPv6, most errors with specifying or omitting scope will result in the socket
630continuing to use (or returning to) the system's default interface selection.
631
632A socket's address family's ANY address (IPv4 `'0.0.0.0'` or IPv6 `'::'`) can be
633used to return control of the sockets default outgoing interface to the system
634for future multicast packets.
635
636### `socket.setMulticastLoopback(flag)`
637<!-- YAML
638added: v0.3.8
639-->
640
641* `flag` {boolean}
642
643Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`,
644multicast packets will also be received on the local interface.
645
646This method throws `EBADF` if called on an unbound socket.
647
648### `socket.setMulticastTTL(ttl)`
649<!-- YAML
650added: v0.3.8
651-->
652
653* `ttl` {integer}
654
655Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
656"Time to Live", in this context it specifies the number of IP hops that a
657packet is allowed to travel through, specifically for multicast traffic. Each
658router or gateway that forwards a packet decrements the TTL. If the TTL is
659decremented to 0 by a router, it will not be forwarded.
660
661The `ttl` argument may be between 0 and 255. The default on most systems is `1`.
662
663This method throws `EBADF` if called on an unbound socket.
664
665### `socket.setRecvBufferSize(size)`
666<!-- YAML
667added: v8.7.0
668-->
669
670* `size` {integer}
671
672Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer
673in bytes.
674
675This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
676
677### `socket.setSendBufferSize(size)`
678<!-- YAML
679added: v8.7.0
680-->
681
682* `size` {integer}
683
684Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer
685in bytes.
686
687This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
688
689### `socket.setTTL(ttl)`
690<!-- YAML
691added: v0.1.101
692-->
693
694* `ttl` {integer}
695
696Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
697in this context it specifies the number of IP hops that a packet is allowed to
698travel through. Each router or gateway that forwards a packet decrements the
699TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
700Changing TTL values is typically done for network probes or when multicasting.
701
702The `ttl` argument may be between between 1 and 255. The default on most systems
703is 64.
704
705This method throws `EBADF` if called on an unbound socket.
706
707### `socket.unref()`
708<!-- YAML
709added: v0.9.1
710-->
711
712* Returns: {dgram.Socket}
713
714By default, binding a socket will cause it to block the Node.js process from
715exiting as long as the socket is open. The `socket.unref()` method can be used
716to exclude the socket from the reference counting that keeps the Node.js
717process active, allowing the process to exit even if the socket is still
718listening.
719
720Calling `socket.unref()` multiple times will have no addition effect.
721
722The `socket.unref()` method returns a reference to the socket so calls can be
723chained.
724
725## `dgram` module functions
726
727### `dgram.createSocket(options[, callback])`
728<!-- YAML
729added: v0.11.13
730changes:
731  - version: v8.6.0
732    pr-url: https://github.com/nodejs/node/pull/14560
733    description: The `lookup` option is supported.
734  - version: v8.7.0
735    pr-url: https://github.com/nodejs/node/pull/13623
736    description: The `recvBufferSize` and `sendBufferSize` options are
737                 supported now.
738  - version: v11.4.0
739    pr-url: https://github.com/nodejs/node/pull/23798
740    description: The `ipv6Only` option is supported.
741-->
742
743* `options` {Object} Available options are:
744  * `type` {string} The family of socket. Must be either `'udp4'` or `'udp6'`.
745    Required.
746  * `reuseAddr` {boolean} When `true` [`socket.bind()`][] will reuse the
747    address, even if another process has already bound a socket on it.
748    **Default:** `false`.
749  * `ipv6Only` {boolean} Setting `ipv6Only` to `true` will
750    disable dual-stack support, i.e., binding to address `::` won't make
751    `0.0.0.0` be bound. **Default:** `false`.
752  * `recvBufferSize` {number} Sets the `SO_RCVBUF` socket value.
753  * `sendBufferSize` {number} Sets the `SO_SNDBUF` socket value.
754  * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
755* `callback` {Function} Attached as a listener for `'message'` events. Optional.
756* Returns: {dgram.Socket}
757
758Creates a `dgram.Socket` object. Once the socket is created, calling
759[`socket.bind()`][] will instruct the socket to begin listening for datagram
760messages. When `address` and `port` are not passed to [`socket.bind()`][] the
761method will bind the socket to the "all interfaces" address on a random port
762(it does the right thing for both `udp4` and `udp6` sockets). The bound address
763and port can be retrieved using [`socket.address().address`][] and
764[`socket.address().port`][].
765
766### `dgram.createSocket(type[, callback])`
767<!-- YAML
768added: v0.1.99
769-->
770
771* `type` {string} Either `'udp4'` or `'udp6'`.
772* `callback` {Function} Attached as a listener to `'message'` events.
773* Returns: {dgram.Socket}
774
775Creates a `dgram.Socket` object of the specified `type`.
776
777Once the socket is created, calling [`socket.bind()`][] will instruct the
778socket to begin listening for datagram messages. When `address` and `port` are
779not passed to [`socket.bind()`][] the method will bind the socket to the "all
780interfaces" address on a random port (it does the right thing for both `udp4`
781and `udp6` sockets). The bound address and port can be retrieved using
782[`socket.address().address`][] and [`socket.address().port`][].
783
784[`'close'`]: #dgram_event_close
785[`ERR_SOCKET_BAD_PORT`]: errors.html#errors_err_socket_bad_port
786[`ERR_SOCKET_BUFFER_SIZE`]: errors.html#errors_err_socket_buffer_size
787[`ERR_SOCKET_DGRAM_IS_CONNECTED`]: errors.html#errors_err_socket_dgram_is_connected
788[`ERR_SOCKET_DGRAM_NOT_CONNECTED`]: errors.html#errors_err_socket_dgram_not_connected
789[`Error`]: errors.html#errors_class_error
790[`System Error`]: errors.html#errors_class_systemerror
791[`close()`]: #dgram_socket_close_callback
792[`cluster`]: cluster.html
793[`connect()`]: #dgram_socket_connect_port_address_callback
794[`dgram.createSocket()`]: #dgram_dgram_createsocket_options_callback
795[`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback
796[`socket.address().address`]: #dgram_socket_address
797[`socket.address().port`]: #dgram_socket_address
798[`socket.bind()`]: #dgram_socket_bind_port_address_callback
799[IPv6 Zone Indices]: https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses
800[RFC 4007]: https://tools.ietf.org/html/rfc4007
801[byte length]: buffer.html#buffer_static_method_buffer_bytelength_string_encoding
802