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