SOLFIND
Web Lens
Portal home

UDP/datagram sockets | Node.js v26.8.2 Documentation

https://nodejs.org/api/dgram.html • 171 KB fetched
Open original page


UDP/datagram sockets | Node.js v26.8.2 Documentation Skip to content Node.js * About this documentation * Usage and example * Assertion testing * Asynchronous context tracking * Async hooks * Buffer * C++ addons * C/C++ addons with Node-API * C++ embedder API * Child processes * Cluster * Command-line options * Console * Crypto * Debugger * Deprecated APIs * Diagnostics Channel * DNS * Domain * Environment Variables * Errors * Events * File system * FFI * Globals * HTTP * HTTP/2 * HTTPS * Inspector * Internationalization * Iterable Streams API * Modules: CommonJS modules * Modules: ECMAScript modules * Modules: node:module API * Modules: Packages * Modules: TypeScript * Net * OS * Path * Performance hooks * Permissions * Process * Punycode * Query strings * Readline * REPL * Report * Single executable applications * SQLite * Stream * String decoder * Test runner * Timers * TLS/SSL * Trace events * TTY * UDP/datagram * URL * Utilities * V8 * Virtual File System * VM * WASI * Web Crypto API * Web Streams API * Worker threads * Zlib * Code repository and issue tracker Node.js v26.8.2 documentation * Node.js v26.8.2 * Table of contents * UDP/datagram sockets * Class: dgram.Socket * Event: 'close' * Event: 'connect' * Event: 'error' * Event: 'listening' * Event: 'message' * socket.addMembership(multicastAddress[, multicastInterface]) * socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface]) * socket.address() * socket.bind([port][, address][, callback]) * socket.bind(options[, callback]) * socket.bindSync([options]) * socket.close([callback]) * socket[Symbol.asyncDispose]() * socket.connect(port[, address][, callback]) * socket.connectSync(port[, address]) * socket.disconnect() * socket.dropMembership(multicastAddress[, multicastInterface]) * socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface]) * socket.getRecvBufferSize() * socket.getSendBufferSize() * socket.getSendQueueSize() * socket.getSendQueueCount() * socket.ref() * socket.remoteAddress() * socket.send(msg[, offset, length][, port][, address][, callback]) * Note about UDP datagram size * socket.setBroadcast(flag) * socket.setMulticastInterface(multicastInterface) * Example: IPv6 outgoing multicast interface * Example: IPv4 outgoing multicast interface * Call results * socket.setMulticastLoopback(flag) * socket.setMulticastTTL(ttl) * socket.setRecvBufferSize(size) * socket.setSendBufferSize(size) * socket.setTTL(ttl) * socket.unref() * node:dgram module functions * dgram.createSocket(options[, callback]) * dgram.createSocket(type[, callback]) * Index * Index * About this documentation * Usage and example * Assertion testing * Asynchronous context tracking * Async hooks * Buffer * C++ addons * C/C++ addons with Node-API * C++ embedder API * Child processes * Cluster * Command-line options * Console * Crypto * Debugger * Deprecated APIs * Diagnostics Channel * DNS * Domain * Environment Variables * Errors * Events * File system * FFI * Globals * HTTP * HTTP/2 * HTTPS * Inspector * Internationalization * Iterable Streams API * Modules: CommonJS modules * Modules: ECMAScript modules * Modules: node:module API * Modules: Packages * Modules: TypeScript * Net * OS * Path * Performance hooks * Permissions * Process * Punycode * Query strings * Readline * REPL * Report * Single executable applications * SQLite * Stream * String decoder * Test runner * Timers * TLS/SSL * Trace events * TTY * UDP/datagram * URL * Utilities * V8 * Virtual File System * VM * WASI * Web Crypto API * Web Streams API * Worker threads * Zlib * Other versions * 26.x * 25.x * 24.x LTS * 23.x * 22.x LTS * 21.x * 20.x * 19.x * 18.x * 17.x * 16.x * 15.x * 14.x * 13.x * 12.x * 11.x * 10.x * 9.x * 8.x * 7.x * 6.x * 5.x * 4.x * 0.12.x * 0.10.x * Options * View on single page * View as JSON * Edit on GitHub Table of contents * UDP/datagram sockets * Class: dgram.Socket * Event: 'close' * Event: 'connect' * Event: 'error' * Event: 'listening' * Event: 'message' * socket.addMembership(multicastAddress[, multicastInterface]) * socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface]) * socket.address() * socket.bind([port][, address][, callback]) * socket.bind(options[, callback]) * socket.bindSync([options]) * socket.close([callback]) * socket[Symbol.asyncDispose]() * socket.connect(port[, address][, callback]) * socket.connectSync(port[, address]) * socket.disconnect() * socket.dropMembership(multicastAddress[, multicastInterface]) * socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface]) * socket.getRecvBufferSize() * socket.getSendBufferSize() * socket.getSendQueueSize() * socket.getSendQueueCount() * socket.ref() * socket.remoteAddress() * socket.send(msg[, offset, length][, port][, address][, callback]) * Note about UDP datagram size * socket.setBroadcast(flag) * socket.setMulticastInterface(multicastInterface) * Example: IPv6 outgoing multicast interface * Example: IPv4 outgoing multicast interface * Call results * socket.setMulticastLoopback(flag) * socket.setMulticastTTL(ttl) * socket.setRecvBufferSize(size) * socket.setSendBufferSize(size) * socket.setTTL(ttl) * socket.unref() * node:dgram module functions * dgram.createSocket(options[, callback]) * dgram.createSocket(type[, callback]) UDP/datagram sockets # Source Code: lib/dgram.js Stability: 2 - Stable The node:dgram module provides an implementation of UDP datagram sockets. import dgram from 'node:dgram' ; const server = dgram . createSocket ( 'udp4' ) ; server . on ( 'error' , ( err ) => { console . error ( `server error: \n ${ err . stack } ` ) ; server . close () ; } ) ; server . on ( 'message' , ( msg , rinfo ) => { console . log ( `server got: ${ msg } from ${ rinfo . address } : ${ rinfo . port } ` ) ; } ) ; server . on ( 'listening' , () => { const address = server . address () ; console . log ( `server listening ${ address . address } : ${ address . port } ` ) ; } ) ; server . bind ( 41234 ) ; // Prints: server listening 0.0.0.0:41234 const dgram = require ( 'node:dgram' ) ; const server = dgram . createSocket ( 'udp4' ) ; server . on ( 'error' , ( err ) => { console . error ( `server error: \n ${ err . stack } ` ) ; server . close () ; } ) ; server . on ( 'message' , ( msg , rinfo ) => { console . log ( `server got: ${ msg } from ${ rinfo . address } : ${ rinfo . port } ` ) ; } ) ; server . on ( 'listening' , () => { const address = server . address () ; console . log ( `server listening ${ address . address } : ${ address . port } ` ) ; } ) ; server . bind ( 41234 ) ; // Prints: server listening 0.0.0.0:41234 javascript copy Class: dgram.Socket # Added in: v0.1.99 * Extends: <EventEmitter> Encapsulates the datagram functionality. New instances of dgram.Socket are created using dgram.createSocket() . The new keyword is not to be used to create dgram.Socket instances. Event: 'close' # Added in: v0.1.99 The 'close' event is emitted after a socket is closed with close() . Once triggered, no new 'message' events will be emitted on this socket. Event: 'connect' # Added in: v12.0.0 The 'connect' event is emitted after a socket is associated to a remote address as a result of a successful connect() call. Event: 'error' # Added in: v0.1.99 * exception   <Error> The 'error' event is emitted whenever any error occurs. The event handler function is passed a single Error object. Event: 'listening' # Added in: v0.1.99 The 'listening' event is emitted once the dgram.Socket is addressable and can receive data. This happens either explicitly with socket.bind() or implicitly the first time data is sent using socket.send() . Until the dgram.Socket is listening, the underlying system resources do not exist and calls such as socket.address() and socket.setTTL() will fail. Event: 'message' # Added in: v0.1.99 History Version Changes v18.4.0 The family property now returns a string instead of a number. v18.0.0 The family property now returns a number instead of a string. The 'message' event is emitted when a new datagram is available on a socket. The event handler function is passed two arguments: msg and rinfo . * msg   <Buffer> The message. * rinfo   <Object> Remote address information. * address   <string> The sender address. * family   <string> The address family ( 'IPv4' or 'IPv6' ). * port   <number> The sender port. * size   <number> The message size. If the source address of the incoming packet is an IPv6 link-local address, the interface name is added to the address . For example, a packet received on the en0 interface might have the address field set to 'fe80::2618:1234:ab11:3b9c%en0' , where '%en0' is the interface name as a zone ID suffix. socket.addMembership(multicastAddress[, multicastInterface]) # Added in: v0.6.9 * multicastAddress   <string> * multicastInterface   <string> Tells the kernel to join a multicast group at the given multicastAddress and multicastInterface using the IP_ADD_MEMBERSHIP socket option. If the multicastInterface argument is not specified, the operating system will choose one interface and will add membership to it. To add membership to every available interface, call addMembership multiple times, once per interface. When called on an unbound socket, this method will implicitly bind to a random port, listening on all interfaces. When sharing a UDP socket across multiple cluster workers, the socket.addMembership() function must be called only once or an EADDRINUSE error will occur: import cluster from 'node:cluster' ; import dgram from 'node:dgram' ; if (cluster . isPrimary) { cluster . fork () ; // Works ok. cluster . fork () ; // Fails with EADDRINUSE. } else { const s = dgram . createSocket ( 'udp4' ) ; s . bind ( 1234 , () => { s . addMembership ( '224.0.0.114' ) ; } ) ; } const cluster = require ( 'node:cluster' ) ; const dgram = require ( 'node:dgram' ) ; if (cluster . isPrimary) { cluster . fork () ; // Works ok. cluster . fork () ; // Fails with EADDRINUSE. } else { const s = dgram . createSocket ( 'udp4' ) ; s . bind ( 1234 , () => { s . addMembership ( '224.0.0.114' ) ; } ) ; } javascript copy socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface]) # Added in: v13.1.0, v12.16.0 * sourceAddress   <string> * groupAddress   <string> * multicastInterface   <string> Tells the kernel to join a source-specific multicast channel at the given sourceAddress and groupAddress , using the multicastInterface with the IP_ADD_SOURCE_MEMBERSHIP socket option. If the multicastInterface argument is not specified, the operating system will choose one interface and will add membership to it. To add membership to every available interface, call socket.addSourceSpecificMembership() multiple times, once per interface. When called on an unbound socket, this method will implicitly bind to a random port, listening on all interfaces. socket.address() # Added in: v0.1.99 * Returns: <Object> Returns an object containing the address information for a socket. For UDP sockets, this object will contain address , family , and port properties. This method throws EBADF if called on an unbound socket. socket.bind([port][, address][, callback]) # Added in: v0.1.99 History Version Changes v0.9.1 The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call. * port   <integer> * address   <string> * callback   <Function> with no parameters. Called when binding is complete. For UDP sockets, causes the dgram.Socket to listen for datagram messages on a named port and optional address . If port is not specified or is 0 , the operating system will attempt to bind to a random port. If address is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a 'listening' event is emitted and the optional callback function is called. Specifying both a 'listening' event listener and passing a callback to the socket.bind() method is not harmful but not very useful. A bound datagram socket keeps the Node.js process running to receive datagram messages. If binding fails, an 'error' event is generated. In rare cases (e.g., attempting to bind with a closed socket), an Error may be thrown. Example of a UDP server listening on port 41234: import dgram from 'node:dgram' ; const server = dgram . createSocket ( 'udp4' ) ; server . on ( 'error' , ( err ) => { console . error ( `server error: \n ${ err . stack } ` ) ; server . close () ; } ) ; server . on ( 'message' , ( msg , rinfo ) => { console . log ( `server got: ${ msg } from ${ rinfo . address } : ${ rinfo . port } ` ) ; } ) ; server . on ( 'listening' , () => { const address = server . address () ; console . log ( `server listening ${ address . address } : ${ address . port } ` ) ; } ) ; server . bind ( 41234 ) ; // Prints: server listening 0.0.0.0:41234 const dgram = require ( 'node:dgram' ) ; const server = dgram . createSocket ( 'udp4' ) ; server . on ( 'error' , ( err ) => { console . error ( `server error: \n ${ err . stack } ` ) ; server . close () ; } ) ; server . on ( 'message' , ( msg , rinfo ) => { console . log ( `server got: ${ msg } from ${ rinfo . address } : ${ rinfo . port } ` ) ; } ) ; server . on ( 'listening' , () => { const address = server . address () ; console . log ( `server listening ${ address . address } : ${ address . port } ` ) ; } ) ; server . bind ( 41234 ) ; // Prints: server listening 0.0.0.0:41234 javascript copy socket.bind(options[, callback]) # Added in: v0.11.14 * options   <Object> Required. Supports the following properties: * port   <integer> * address   <string> * exclusive   <boolean> * fd   <integer> * callback   <Function> For UDP sockets, causes the dgram.Socket to listen for datagram messages on a named port and optional address that are passed as properties of an options object passed as the first argument. If port is not specified or is 0 , the operating system will attempt to bind to a random port. If address is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a 'listening' event is emitted and the optional callback function is called. The options object may contain a fd property. When a fd greater than 0 is set, it will wrap around an existing socket with the given file descriptor. In this case, the properties of port and address will be ignored. Specifying both a 'listening' event listener and passing a callback to the socket.bind() method is not harmful but not very useful. The options object may contain an additional exclusive property that is used when using dgram.Socket objects with the cluster module. When exclusive is set to false (the default), cluster workers will use the same underlying socket handle allowing connection handling duties to be shared. When exclusive is true , however, the handle is not shared and attempted port sharing results in an error. Creating a dgram.Socket with the reusePort option set to true causes exclusive to always be true when socket.bind() is called. A bound datagram socket keeps the Node.js process running to receive datagram messages. If binding fails, an 'error' event is generated. In rare cases (e.g., attempting to bind with a closed socket), an Error may be thrown. An example socket listening on an exclusive port is shown below. socket . bind ( { address : 'localhost' , port : 8000 , exclusive : true , } ) ; js copy socket.bindSync([options]) # Added in: v26.4.0 * options   <Object> * port   <integer> If omitted or  0 , the operating system will assign an arbitrary unused port. Default: 0 . * address   <string> A numeric IP address to bind to. Unlike  socket.bind() , no DNS resolution is performed, so a host name is not accepted. If omitted, the operating system binds to all addresses ( '0.0.0.0' for udp4 sockets, '::' for udp6 ). * Returns: <Object> The bound address as returned by  socket.address() . The synchronous counterpart of socket.bind() . bind(2) is a local, non-blocking system call, so the bind is performed inline and the resolved address is returned immediately, including the operating-system-assigned ephemeral port when port is 0 : const dgram = require ( 'node:dgram' ) ; const socket = dgram . createSocket ( 'udp4' ) ; const address = socket . bindSync ( { address : '0.0.0.0' , port : 0 } ) ; console . log (address) ; // e.g. { address: '0.0.0.0', family: 'IPv4', port: 53124 } js copy A bind failure such as EADDRINUSE is thrown synchronously rather than emitted as an 'error' event. After bindSync() returns, socket.address() is valid synchronously and the 'listening' event is emitted on the next tick. address must be a numeric IP literal; bindSync() never performs DNS resolution (asynchronous name resolution being the only genuinely blocking part of binding). Incoming datagrams continue to be delivered asynchronously via the 'message' event. bindSync() always binds the socket's own handle and does not participate in cluster handle sharing. socket.close([callback]) # Added in: v0.1.99 * callback   <Function> Called when the socket has been closed. Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the 'close' event. socket[Symbol.asyncDispose]() # Added in: v20.5.0, v18.18.0 History Version Changes v24.2.0 No longer experimental. Calls socket.close() and returns a promise that fulfills when the socket has closed. socket.connect(port[, address][, callback]) # Added in: v12.0.0 * port   <integer> * address   <string> * callback   <Function> Called when the connection is completed or on error. Associates the dgram.Socket to a remote address and port.

Links found on this page

  1. Skip to content [direct]
  2. Node.js [direct]
  3. About this documentation [direct]
  4. Usage and example [direct]
  5. Assertion testing [direct]
  6. Asynchronous context tracking [direct]
  7. Async hooks [direct]
  8. Buffer [direct]
  9. C++ addons [direct]
  10. C/C++ addons with Node-API [direct]
  11. C++ embedder API [direct]
  12. Child processes [direct]
  13. Cluster [direct]
  14. Command-line options [direct]
  15. Console [direct]
  16. Crypto [direct]
  17. Debugger [direct]
  18. Deprecated APIs [direct]
  19. Diagnostics Channel [direct]
  20. DNS [direct]
  21. Domain [direct]
  22. Environment Variables [direct]
  23. Errors [direct]
  24. Events [direct]
  25. File system [direct]
  26. FFI [direct]
  27. Globals [direct]
  28. HTTP [direct]
  29. HTTP/2 [direct]
  30. HTTPS [direct]
  31. Inspector [direct]
  32. Internationalization [direct]
  33. Iterable Streams API [direct]
  34. Modules: CommonJS modules [direct]
  35. Modules: ECMAScript modules [direct]
  36. Modules: node:module API [direct]
  37. Modules: Packages [direct]
  38. Modules: TypeScript [direct]
  39. Net [direct]
  40. OS [direct]
  41. Path [direct]
  42. Performance hooks [direct]
  43. Permissions [direct]
  44. Process [direct]
  45. Punycode [direct]
  46. Query strings [direct]
  47. Readline [direct]
  48. REPL [direct]
  49. Report [direct]
  50. Single executable applications [direct]
  51. SQLite [direct]
  52. Stream [direct]
  53. String decoder [direct]
  54. Test runner [direct]
  55. Timers [direct]
  56. TLS/SSL [direct]
  57. Trace events [direct]
  58. TTY [direct]
  59. URL [direct]
  60. Utilities [direct]
  61. V8 [direct]
  62. Virtual File System [direct]
  63. VM [direct]
  64. WASI [direct]
  65. Web Crypto API [direct]
  66. Web Streams API [direct]
  67. Worker threads [direct]
  68. Zlib [direct]
  69. Code repository and issue tracker [direct]
  70. Index [direct]
  71. 26.x [direct]
  72. 25.x [direct]
  73. 24.x LTS [direct]
  74. 23.x [direct]
  75. 22.x LTS [direct]
  76. 21.x [direct]
  77. 20.x [direct]
  78. 19.x [direct]
  79. 18.x [direct]
  80. 17.x [direct]