Node.js v24.2.0 documentation
- Node.js v24.2.0
-
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.close([callback])socket[Symbol.asyncDispose]()socket.connect(port[, address][, callback])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])socket.setBroadcast(flag)socket.setMulticastInterface(multicastInterface)socket.setMulticastLoopback(flag)socket.setMulticastTTL(ttl)socket.setRecvBufferSize(size)socket.setSendBufferSize(size)socket.setTTL(ttl)socket.unref()
- Event:
node:dgrammodule functions
- Class:
- UDP/datagram sockets
-
Index
- 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
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:moduleAPI - 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
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- Other versions
- Options
UDP/datagram sockets#
Source Code: lib/dgram.js
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:41234const 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
Class: dgram.Socket#
- 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'#
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'#
The 'connect' event is emitted after a socket is associated to a remote
address as a result of a successful connect() call.
Event: 'error'#
exception<Error>
The 'error' event is emitted whenever any error occurs. The event handler
function is passed a single Error object.
Event: 'listening'#
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'#
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.
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])#
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');
});
}
socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])#
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()#
- 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.