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