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
- Skip to content [direct]
- Node.js [direct]
- About this documentation [direct]
- Usage and example [direct]
- Assertion testing [direct]
- Asynchronous context tracking [direct]
- Async hooks [direct]
- Buffer [direct]
- C++ addons [direct]
- C/C++ addons with Node-API [direct]
- C++ embedder API [direct]
- Child processes [direct]
- Cluster [direct]
- Command-line options [direct]
- Console [direct]
- Crypto [direct]
- Debugger [direct]
- Deprecated APIs [direct]
- Diagnostics Channel [direct]
- DNS [direct]
- Domain [direct]
- Environment Variables [direct]
- Errors [direct]
- Events [direct]
- File system [direct]
- FFI [direct]
- Globals [direct]
- HTTP [direct]
- HTTP/2 [direct]
- HTTPS [direct]
- Inspector [direct]
- Internationalization [direct]
- Iterable Streams API [direct]
- Modules: CommonJS modules [direct]
- Modules: ECMAScript modules [direct]
- Modules: node:module API [direct]
- Modules: Packages [direct]
- Modules: TypeScript [direct]
- Net [direct]
- OS [direct]
- Path [direct]
- Performance hooks [direct]
- Permissions [direct]
- Process [direct]
- Punycode [direct]
- Query strings [direct]
- Readline [direct]
- REPL [direct]
- Report [direct]
- Single executable applications [direct]
- SQLite [direct]
- Stream [direct]
- String decoder [direct]
- Test runner [direct]
- Timers [direct]
- TLS/SSL [direct]
- Trace events [direct]
- TTY [direct]
- URL [direct]
- Utilities [direct]
- V8 [direct]
- Virtual File System [direct]
- VM [direct]
- WASI [direct]
- Web Crypto API [direct]
- Web Streams API [direct]
- Worker threads [direct]
- Zlib [direct]
- Code repository and issue tracker [direct]
- Index [direct]
- 26.x [direct]
- 25.x [direct]
- 24.x LTS [direct]
- 23.x [direct]
- 22.x LTS [direct]
- 21.x [direct]
- 20.x [direct]
- 19.x [direct]
- 18.x [direct]
- 17.x [direct]