{ "source": "doc/api/dgram.md", "modules": [ { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
The 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// server listening 0.0.0.0:41234\n
\n",
"classes": [
{
"textRaw": "Class: dgram.Socket",
"type": "class",
"name": "dgram.Socket",
"meta": {
"added": [
"v0.1.99"
],
"changes": []
},
"desc": "The dgram.Socket
object is an EventEmitter
that encapsulates the\ndatagram functionality.
New 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 'error'
event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.
The 'listening'
event is emitted whenever a socket begins listening for\ndatagram messages. This occurs as soon as UDP sockets are created.
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
.
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.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.
Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address
, family
and port
\nproperties.
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.
Note that 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// server listening 0.0.0.0:41234\n
\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: ",
"options": [
{
"textRaw": "`port` {integer} ",
"name": "port",
"type": "integer"
},
{
"textRaw": "`address` {string} ",
"name": "address",
"type": "string"
},
{
"textRaw": "`exclusive` {boolean} ",
"name": "exclusive",
"type": "boolean"
}
],
"name": "options",
"type": "Object",
"desc": "Required. Supports the following properties:"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"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.
Note that 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\nuse 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
\n"
},
{
"textRaw": "socket.close([callback])",
"type": "method",
"name": "close",
"meta": {
"added": [
"v0.1.99"
],
"changes": []
},
"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.
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.
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.
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.
Broadcasts a datagram on the socket. The destination port
and address
must\nbe specified.
The msg
argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg
is a Buffer
\nor Uint8Array
,\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.\nNote that DNS 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
or Uint8Array
.
Example of sending a UDP packet to a random 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 random port\non 127.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. It is important to run benchmarks to\ndetermine the optimal strategy on a case-by-case basis. Generally speaking,\nhowever, sending multiple buffers is faster.
\nA Note about UDP datagram size
\nThe 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 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.
Note: 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 or\ninterface 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.
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
\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.
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 argument passed to socket.setMulticastTTL()
is a number of hops\nbetween 0 and 255. The default on most systems is 1
but can vary.
Sets the SO_RCVBUF
socket option. Sets the maximum socket receive buffer\nin bytes.
Sets the SO_SNDBUF
socket option. Sets the maximum socket send buffer\nin bytes.
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 argument to socket.setTTL()
is a number of hops between 1 and 255.\nThe default on most systems is 64 but can vary.
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.
As of Node.js v0.10, dgram.Socket#bind()
changed to an asynchronous\nexecution model. Legacy code that assumes synchronous behavior, as in the\nfollowing example:
const s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');\n
\nMust be changed to pass a callback function to the dgram.Socket#bind()
\nfunction:
const s = dgram.createSocket('udp4');\ns.bind(1234, () => {\n s.addMembership('224.0.0.114');\n});\n
\n",
"type": "module",
"displayName": "Change to asynchronous `socket.bind()` behavior"
}
]
}
],
"modules": [
{
"textRaw": "`dgram` module functions",
"name": "`dgram`_module_functions",
"methods": [
{
"textRaw": "dgram.createSocket(options[, callback])",
"type": "method",
"name": "createSocket",
"meta": {
"added": [
"v0.11.13"
],
"changes": [
{
"version": "v8.6.0",
"pr-url": "https://github.com/nodejs/node/pull/14560",
"description": "The `lookup` option is supported."
},
{
"version": "v8.7.0",
"pr-url": "https://github.com/nodejs/node/pull/13623",
"description": "The `recvBufferSize` and `sendBufferSize` options are supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {dgram.Socket} ",
"name": "return",
"type": "dgram.Socket"
},
"params": [
{
"textRaw": "`options` {Object} Available options are: ",
"options": [
{
"textRaw": "`type` {string} The family of socket. Must be either `'udp4'` or `'udp6'`. Required. ",
"name": "type",
"type": "string",
"desc": "The family of socket. Must be either `'udp4'` or `'udp6'`. Required."
},
{
"textRaw": "`reuseAddr` {boolean} When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it. Defaults to `false`. ",
"name": "reuseAddr",
"type": "boolean",
"desc": "When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it. Defaults to `false`."
},
{
"textRaw": "`recvBufferSize` {number} - Sets the `SO_RCVBUF` socket value. ",
"name": "recvBufferSize",
"type": "number",
"desc": "Sets the `SO_RCVBUF` socket value."
},
{
"textRaw": "`sendBufferSize` {number} - Sets the `SO_SNDBUF` socket value. ",
"name": "sendBufferSize",
"type": "number",
"desc": "Sets the `SO_SNDBUF` socket value."
},
{
"textRaw": "`lookup` {Function} Custom lookup function. Defaults to [`dns.lookup()`][]. ",
"name": "lookup",
"type": "Function",
"desc": "Custom lookup function. Defaults to [`dns.lookup()`][]."
}
],
"name": "options",
"type": "Object",
"desc": "Available options are:"
},
{
"textRaw": "`callback` {Function} Attached as a listener for `'message'` events. Optional. ",
"name": "callback",
"type": "Function",
"desc": "Attached as a listener for `'message'` events. Optional.",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "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
.
Creates a dgram.Socket
object of the specified type
. The type
argument\ncan be either udp4
or udp6
. An optional callback
function can be passed\nwhich is added as a listener for 'message'
events.
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
.