{ "type": "module", "source": "doc/api/dgram.md", "modules": [ { "textRaw": "UDP/datagram sockets", "name": "dgram", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/dgram.js
\nThe dgram
module provides an implementation of UDP datagram sockets.
const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n console.log(`server error:\\n${err.stack}`);\n server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n const address = server.address();\n console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
",
"classes": [
{
"textRaw": "Class: `dgram.Socket`",
"type": "class",
"name": "dgram.Socket",
"meta": {
"added": [
"v0.1.99"
],
"changes": []
},
"desc": "Encapsulates the datagram functionality.
\nNew instances of dgram.Socket
are created using dgram.createSocket()
.\nThe new
keyword is not to be used to create dgram.Socket
instances.
The 'close'
event is emitted after a socket is closed with close()
.\nOnce triggered, no new 'message'
events will be emitted on this socket.
The 'connect'
event is emitted after a socket is associated to a remote\naddress as a result of a successful connect()
call.
The 'error'
event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error
object.
The 'listening'
event is emitted once the dgram.Socket
is addressable and\ncan receive data. This happens either explicitly with socket.bind()
or\nimplicitly the first time data is sent using socket.send()
.\nUntil the dgram.Socket
is listening, the underlying system resources do not\nexist and calls such as socket.address()
and socket.setTTL()
will fail.
The 'message'
event is emitted when a new datagram is available on a socket.\nThe event handler function is passed two arguments: msg
and rinfo
.
If the source address of the incoming packet is an IPv6 link-local\naddress, the interface name is added to the address
. For\nexample, a packet received on the en0
interface might have the\naddress field set to 'fe80::2618:1234:ab11:3b9c%en0'
, where '%en0'
\nis the interface name as a zone ID suffix.
Tells the kernel to join a multicast group at the given multicastAddress
and\nmulticastInterface
using the IP_ADD_MEMBERSHIP
socket option. If the\nmulticastInterface
argument is not specified, the operating system will choose\none interface and will add membership to it. To add membership to every\navailable interface, call addMembership
multiple times, once per interface.
When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.
\nWhen sharing a UDP socket across multiple cluster
workers, the\nsocket.addMembership()
function must be called only once or an\nEADDRINUSE
error will occur:
const cluster = require('cluster');\nconst dgram = require('dgram');\nif (cluster.isMaster) {\n cluster.fork(); // Works ok.\n cluster.fork(); // Fails with EADDRINUSE.\n} else {\n const s = dgram.createSocket('udp4');\n s.bind(1234, () => {\n s.addMembership('224.0.0.114');\n });\n}\n
"
},
{
"textRaw": "`socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`",
"type": "method",
"name": "addSourceSpecificMembership",
"meta": {
"added": [
"v13.1.0",
"v12.16.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`sourceAddress` {string}",
"name": "sourceAddress",
"type": "string"
},
{
"textRaw": "`groupAddress` {string}",
"name": "groupAddress",
"type": "string"
},
{
"textRaw": "`multicastInterface` {string}",
"name": "multicastInterface",
"type": "string"
}
]
}
],
"desc": "Tells the kernel to join a source-specific multicast channel at the given\nsourceAddress
and groupAddress
, using the multicastInterface
with the\nIP_ADD_SOURCE_MEMBERSHIP
socket option. If the multicastInterface
argument\nis not specified, the operating system will choose one interface and will add\nmembership to it. To add membership to every available interface, call\nsocket.addSourceSpecificMembership()
multiple times, once per interface.
When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.
" }, { "textRaw": "`socket.address()`", "type": "method", "name": "address", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address
, family
and port
\nproperties.
This method throws EBADF
if called on an unbound socket.
For UDP sockets, causes the dgram.Socket
to listen for datagram\nmessages on a named port
and optional address
. If port
is not\nspecified or is 0
, the operating system will attempt to bind to a\nrandom port. If address
is not specified, the operating system will\nattempt to listen on all addresses. Once binding is complete, a\n'listening'
event is emitted and the optional callback
function is\ncalled.
Specifying both a 'listening'
event listener and passing a\ncallback
to the socket.bind()
method is not harmful but not very\nuseful.
A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.
\nIf binding fails, an 'error'
event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error
may be thrown.
Example of a UDP server listening on port 41234:
\nconst dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n console.log(`server error:\\n${err.stack}`);\n server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n const address = server.address();\n console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
"
},
{
"textRaw": "`socket.bind(options[, callback])`",
"type": "method",
"name": "bind",
"meta": {
"added": [
"v0.11.14"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} Required. Supports the following properties:",
"name": "options",
"type": "Object",
"desc": "Required. Supports the following properties:",
"options": [
{
"textRaw": "`port` {integer}",
"name": "port",
"type": "integer"
},
{
"textRaw": "`address` {string}",
"name": "address",
"type": "string"
},
{
"textRaw": "`exclusive` {boolean}",
"name": "exclusive",
"type": "boolean"
},
{
"textRaw": "`fd` {integer}",
"name": "fd",
"type": "integer"
}
]
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function"
}
]
}
],
"desc": "For UDP sockets, causes the dgram.Socket
to listen for datagram\nmessages on a named port
and optional address
that are passed as\nproperties of an options
object passed as the first argument. If\nport
is not specified or is 0
, the operating system will attempt\nto bind to a random port. If address
is not specified, the operating\nsystem will attempt to listen on all addresses. Once binding is\ncomplete, a 'listening'
event is emitted and the optional callback
\nfunction is called.
The options
object may contain a fd
property. When a fd
greater\nthan 0
is set, it will wrap around an existing socket with the given\nfile descriptor. In this case, the properties of port
and address
\nwill be ignored.
Specifying both a 'listening'
event listener and passing a\ncallback
to the socket.bind()
method is not harmful but not very\nuseful.
The options
object may contain an additional exclusive
property that is\nused when using dgram.Socket
objects with the cluster
module. When\nexclusive
is set to false
(the default), cluster workers will use the same\nunderlying socket handle allowing connection handling duties to be shared.\nWhen exclusive
is true
, however, the handle is not shared and attempted\nport sharing results in an error.
A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.
\nIf binding fails, an 'error'
event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error
may be thrown.
An example socket listening on an exclusive port is shown below.
\nsocket.bind({\n address: 'localhost',\n port: 8000,\n exclusive: true\n});\n
"
},
{
"textRaw": "`socket.close([callback])`",
"type": "method",
"name": "close",
"meta": {
"added": [
"v0.1.99"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function} Called when the socket has been closed.",
"name": "callback",
"type": "Function",
"desc": "Called when the socket has been closed."
}
]
}
],
"desc": "Close the underlying socket and stop listening for data on it. If a callback is\nprovided, it is added as a listener for the 'close'
event.
Associates the dgram.Socket
to a remote address and port. Every\nmessage sent by this handle is automatically sent to that destination. Also,\nthe socket will only receive messages from that remote peer.\nTrying to call connect()
on an already connected socket will result\nin an ERR_SOCKET_DGRAM_IS_CONNECTED
exception. If address
is not\nprovided, '127.0.0.1'
(for udp4
sockets) or '::1'
(for udp6
sockets)\nwill be used by default. Once the connection is complete, a 'connect'
event\nis emitted and the optional callback
function is called. In case of failure,\nthe callback
is called or, failing this, an 'error'
event is emitted.
A synchronous function that disassociates a connected dgram.Socket
from\nits remote address. Trying to call disconnect()
on an unbound or already\ndisconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED
\nexception.
Instructs the kernel to leave a multicast group at multicastAddress
using the\nIP_DROP_MEMBERSHIP
socket option. This method is automatically called by the\nkernel when the socket is closed or the process terminates, so most apps will\nnever have reason to call this.
If multicastInterface
is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.
Instructs the kernel to leave a source-specific multicast channel at the given\nsourceAddress
and groupAddress
using the IP_DROP_SOURCE_MEMBERSHIP
\nsocket option. This method is automatically called by the kernel when the\nsocket is closed or the process terminates, so most apps will never have\nreason to call this.
If multicastInterface
is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.
This method throws ERR_SOCKET_BUFFER_SIZE
if called on an unbound socket.
This method throws ERR_SOCKET_BUFFER_SIZE
if called on an unbound socket.
By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref()
method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active. The socket.ref()
method adds the socket back to the reference\ncounting and restores the default behavior.
Calling socket.ref()
multiples times will have no additional effect.
The socket.ref()
method returns a reference to the socket so calls can be\nchained.
Returns an object containing the address
, family
, and port
of the remote\nendpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED
exception\nif the socket is not connected.
Broadcasts a datagram on the socket.\nFor connectionless sockets, the destination port
and address
must be\nspecified. Connected sockets, on the other hand, will use their associated\nremote endpoint, so the port
and address
arguments must not be set.
The msg
argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg
is a Buffer
,\nany TypedArray
or a DataView
,\nthe offset
and length
specify the offset within the Buffer
where the\nmessage begins and the number of bytes in the message, respectively.\nIf msg
is a String
, then it is automatically converted to a Buffer
\nwith 'utf8'
encoding. With messages that\ncontain multi-byte characters, offset
and length
will be calculated with\nrespect to byte length and not the character position.\nIf msg
is an array, offset
and length
must not be specified.
The address
argument is a string. If the value of address
is a host name,\nDNS will be used to resolve the address of the host. If address
is not\nprovided or otherwise falsy, '127.0.0.1'
(for udp4
sockets) or '::1'
\n(for udp6
sockets) will be used by default.
If the socket has not been previously bound with a call to bind
, the socket\nis assigned a random port number and is bound to the \"all interfaces\" address\n('0.0.0.0'
for udp4
sockets, '::0'
for udp6
sockets.)
An optional callback
function may be specified to as a way of reporting\nDNS errors or for determining when it is safe to reuse the buf
object.\nDNS lookups delay the time to send for at least one tick of the\nNode.js event loop.
The only way to know for sure that the datagram has been sent is by using a\ncallback
. If an error occurs and a callback
is given, the error will be\npassed as the first argument to the callback
. If a callback
is not given,\nthe error is emitted as an 'error'
event on the socket
object.
Offset and length are optional but both must be set if either are used.\nThey are supported only when the first argument is a Buffer
, a TypedArray
,\nor a DataView
.
This method throws ERR_SOCKET_BAD_PORT
if called on an unbound socket.
Example of sending a UDP packet to a port on localhost
;
const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n client.close();\n});\n
\nExample of sending a UDP packet composed of multiple buffers to a port on\n127.0.0.1
;
const dgram = require('dgram');\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, (err) => {\n client.close();\n});\n
\nSending multiple buffers might be faster or slower depending on the\napplication and operating system. Run benchmarks to\ndetermine the optimal strategy on a case-by-case basis. Generally speaking,\nhowever, sending multiple buffers is faster.
\nExample of sending a UDP packet using a socket connected to a port on\nlocalhost
:
const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.connect(41234, 'localhost', (err) => {\n client.send(message, (err) => {\n client.close();\n });\n});\n
",
"modules": [
{
"textRaw": "Note about UDP datagram size",
"name": "note_about_udp_datagram_size",
"desc": "The maximum size of an IPv4/v6 datagram depends on the MTU
\n(Maximum Transmission Unit) and on the Payload Length
field size.
The Payload Length
field is 16 bits wide, which means that a normal\npayload cannot exceed 64K octets including the internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagram\nmessages are impractical for most hosts and networks.
The MTU
is the largest size a given link layer technology can support for\ndatagram messages. For any link, IPv4 mandates a minimum MTU
of 68\noctets, while the recommended MTU
for IPv4 is 576 (typically recommended\nas the MTU
for dial-up type applications), whether they arrive whole or in\nfragments.
For IPv6, the minimum MTU
is 1280 octets. However, the mandatory minimum\nfragment reassembly buffer size is 1500 octets. The value of 68 octets is\nvery small, since most current link layer technologies, like Ethernet, have a\nminimum MTU
of 1500.
It is impossible to know in advance the MTU of each link through which\na packet might travel. Sending a datagram greater than the receiver MTU
will\nnot work because the packet will get silently dropped without informing the\nsource that the data did not reach its intended recipient.
Sets or clears the SO_BROADCAST
socket option. When set to true
, UDP\npackets may be sent to a local interface's broadcast address.
This method throws EBADF
if called on an unbound socket.
All references to scope in this section are referring to\nIPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP\nwith a scope index is written as 'IP%scope'
where scope is an interface name\nor interface number.
Sets the default outgoing multicast interface of the socket to a chosen\ninterface or back to system interface selection. The multicastInterface
must\nbe a valid string representation of an IP from the socket's family.
For IPv4 sockets, this should be the IP configured for the desired physical\ninterface. All packets sent to multicast on the socket will be sent on the\ninterface determined by the most recent successful use of this call.
\nFor IPv6 sockets, multicastInterface
should include a scope to indicate the\ninterface as in the examples that follow. In IPv6, individual send
calls can\nalso use explicit scope in addresses, so only packets sent to a multicast\naddress without specifying an explicit scope are affected by the most recent\nsuccessful use of this call.
This method throws EBADF
if called on an unbound socket.
On most systems, where scope format uses the interface name:
\nconst socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n socket.setMulticastInterface('::%eth1');\n});\n
\nOn Windows, where scope format uses an interface number:
\nconst socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n socket.setMulticastInterface('::%2');\n});\n
\nAll systems use an IP of the host on the desired physical interface:
\nconst socket = dgram.createSocket('udp4');\n\nsocket.bind(1234, () => {\n socket.setMulticastInterface('10.0.0.2');\n});\n
",
"modules": [
{
"textRaw": "Call results",
"name": "call_results",
"desc": "A call on a socket that is not ready to send or no longer open may throw a Not\nrunning Error
.
If multicastInterface
can not be parsed into an IP then an EINVAL\nSystem Error
is thrown.
On IPv4, if multicastInterface
is a valid address but does not match any\ninterface, or if the address does not match the family then\na System Error
such as EADDRNOTAVAIL
or EPROTONOSUP
is thrown.
On IPv6, most errors with specifying or omitting scope will result in the socket\ncontinuing to use (or returning to) the system's default interface selection.
\nA socket's address family's ANY address (IPv4 '0.0.0.0'
or IPv6 '::'
) can be\nused to return control of the sockets default outgoing interface to the system\nfor future multicast packets.
Sets or clears the IP_MULTICAST_LOOP
socket option. When set to true
,\nmulticast packets will also be received on the local interface.
This method throws EBADF
if called on an unbound socket.
Sets the IP_MULTICAST_TTL
socket option. While TTL generally stands for\n\"Time to Live\", in this context it specifies the number of IP hops that a\npacket is allowed to travel through, specifically for multicast traffic. Each\nrouter or gateway that forwards a packet decrements the TTL. If the TTL is\ndecremented to 0 by a router, it will not be forwarded.
The ttl
argument may be between 0 and 255. The default on most systems is 1
.
This method throws EBADF
if called on an unbound socket.
Sets the SO_RCVBUF
socket option. Sets the maximum socket receive buffer\nin bytes.
This method throws ERR_SOCKET_BUFFER_SIZE
if called on an unbound socket.
Sets the SO_SNDBUF
socket option. Sets the maximum socket send buffer\nin bytes.
This method throws ERR_SOCKET_BUFFER_SIZE
if called on an unbound socket.
Sets the IP_TTL
socket option. While TTL generally stands for \"Time to Live\",\nin this context it specifies the number of IP hops that a packet is allowed to\ntravel through. Each router or gateway that forwards a packet decrements the\nTTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\nChanging TTL values is typically done for network probes or when multicasting.
The ttl
argument may be between between 1 and 255. The default on most systems\nis 64.
This method throws EBADF
if called on an unbound socket.
By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref()
method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active, allowing the process to exit even if the socket is still\nlistening.
Calling socket.unref()
multiple times will have no addition effect.
The socket.unref()
method returns a reference to the socket so calls can be\nchained.
Creates a dgram.Socket
object. Once the socket is created, calling\nsocket.bind()
will instruct the socket to begin listening for datagram\nmessages. When address
and port
are not passed to socket.bind()
the\nmethod will bind the socket to the \"all interfaces\" address on a random port\n(it does the right thing for both udp4
and udp6
sockets). The bound address\nand port can be retrieved using socket.address().address
and\nsocket.address().port
.
If the signal
option is enabled, calling .abort()
on the corresponding\nAbortController
is similar to calling .close()
on the socket:
const controller = new AbortController();\nconst { signal } = controller;\nconst server = dgram.createSocket({ type: 'udp4', signal });\nserver.on('message', (msg, rinfo) => {\n console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n// Later, when you want to close the server.\ncontroller.abort();\n
"
},
{
"textRaw": "`dgram.createSocket(type[, callback])`",
"type": "method",
"name": "createSocket",
"meta": {
"added": [
"v0.1.99"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {dgram.Socket}",
"name": "return",
"type": "dgram.Socket"
},
"params": [
{
"textRaw": "`type` {string} Either `'udp4'` or `'udp6'`.",
"name": "type",
"type": "string",
"desc": "Either `'udp4'` or `'udp6'`."
},
{
"textRaw": "`callback` {Function} Attached as a listener to `'message'` events.",
"name": "callback",
"type": "Function",
"desc": "Attached as a listener to `'message'` events."
}
]
}
],
"desc": "Creates a dgram.Socket
object of the specified type
.
Once the socket is created, calling socket.bind()
will instruct the\nsocket to begin listening for datagram messages. When address
and port
are\nnot passed to socket.bind()
the method will bind the socket to the \"all\ninterfaces\" address on a random port (it does the right thing for both udp4
\nand udp6
sockets). The bound address and port can be retrieved using\nsocket.address().address
and socket.address().port
.