{ "source": "doc/api/dgram.md", "modules": [ { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "stability": 2, "stabilityText": "Stable", "desc": "

The dgram module provides an implementation of UDP Datagram sockets.

\n
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  var 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" ] }, "desc": "

The dgram.Socket object is an EventEmitter that encapsulates the\ndatagram functionality.

\n

New instances of dgram.Socket are created using dgram.createSocket().\nThe new keyword is not to be used to create dgram.Socket instances.

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.99" ] }, "desc": "

The 'close' event is emitted after a socket is closed with close().\nOnce triggered, no new 'message' events will be emitted on this socket.

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.1.99" ] }, "params": [], "desc": "

The 'error' event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.

\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.1.99" ] }, "desc": "

The 'listening' event is emitted whenever a socket begins listening for\ndatagram messages. This occurs as soon as UDP sockets are created.

\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.1.99" ] }, "desc": "

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.

\n\n", "params": [] } ], "methods": [ { "textRaw": "socket.addMembership(multicastAddress[, multicastInterface])", "type": "method", "name": "addMembership", "meta": { "added": [ "v0.6.9" ] }, "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {String} ", "name": "multicastAddress", "type": "String" }, { "textRaw": "`multicastInterface` {String}, Optional ", "name": "multicastInterface", "type": "String", "optional": true } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

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.

\n" }, { "textRaw": "socket.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.1.99" ] }, "desc": "

Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address, family and port\nproperties.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.bind([port][, address][, callback])", "type": "method", "name": "bind", "meta": { "added": [ "v0.1.99" ] }, "signatures": [ { "params": [ { "textRaw": "`port` {Number} - Integer, Optional ", "name": "port", "type": "Number", "optional": true, "desc": "Integer" }, { "textRaw": "`address` {String}, Optional ", "name": "address", "type": "String", "optional": true }, { "textRaw": "`callback` {Function} with no parameters, Optional. Called when binding is complete. ", "name": "callback", "type": "Function", "desc": "with no parameters, Optional. Called when binding is complete.", "optional": true } ] }, { "params": [ { "name": "port", "optional": true }, { "name": "address", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

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.

\n

Note that specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

\n

A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

\n

If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

\n

Example of a UDP server listening on port 41234:

\n
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  var 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" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} - Required. Supports the following properties: ", "options": [ { "textRaw": "`port` {Number} - Optional. ", "name": "port", "type": "Number", "desc": "Optional." }, { "textRaw": "`address` {String} - Optional. ", "name": "address", "type": "String", "desc": "Optional." }, { "textRaw": "`exclusive` {Boolean} - Optional. ", "name": "exclusive", "type": "Boolean", "desc": "Optional." } ], "name": "options", "type": "Object", "desc": "Required. Supports the following properties:" }, { "textRaw": "`callback` {Function} - Optional. ", "name": "callback", "type": "Function", "desc": "Optional.", "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.

\n

Note that specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

\n

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.

\n

A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

\n

If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

\n

An example socket listening on an exclusive port is shown below.

\n
socket.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" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.dropMembership(multicastAddress[, multicastInterface])", "type": "method", "name": "dropMembership", "meta": { "added": [ "v0.6.9" ] }, "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {String} ", "name": "multicastAddress", "type": "String" }, { "textRaw": "`multicastInterface` {String}, Optional ", "name": "multicastInterface", "type": "String", "optional": true } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

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.

\n

If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

\n" }, { "textRaw": "socket.send(msg, [offset, length,] port, address[, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.1.99" ] }, "signatures": [ { "params": [ { "textRaw": "`msg` {Buffer|String|Array} Message to be sent ", "name": "msg", "type": "Buffer|String|Array", "desc": "Message to be sent" }, { "textRaw": "`offset` {Number} Integer. Optional. Offset in the buffer where the message starts. ", "name": "offset", "type": "Number", "desc": "Integer. Optional. Offset in the buffer where the message starts.", "optional": true }, { "textRaw": "`length` {Number} Integer. Optional. Number of bytes in the message. ", "name": "length", "type": "Number", "desc": "Integer. Optional. Number of bytes in the message.", "optional": true }, { "textRaw": "`port` {Number} Integer. Destination port. ", "name": "port", "type": "Number", "desc": "Integer. Destination port." }, { "textRaw": "`address` {String} Destination hostname or IP address. ", "name": "address", "type": "String", "desc": "Destination hostname or IP address." }, { "textRaw": "`callback` {Function} Called when the message has been sent. Optional. ", "name": "callback", "type": "Function", "desc": "Called when the message has been sent. Optional.", "optional": true } ] }, { "params": [ { "name": "msg" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "port" }, { "name": "address" }, { "name": "callback", "optional": true } ] } ], "desc": "

Broadcasts a datagram on the socket. The destination port and address must\nbe specified.

\n

The msg argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg is a Buffer,\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.

\n

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 the address is not\nspecified or is an empty string, '127.0.0.1' or '::1' will be used instead.

\n

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.)

\n

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.

\n

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.

\n

Offset and length are optional, but if you specify one you would need to\nspecify the other. Also, they are supported only when the first\nargument is a Buffer.

\n

Example of sending a UDP packet to a random port on localhost;

\n
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
\n

Example of sending a UDP packet composed of multiple buffers to a random port on localhost;

\n
const dgram = require('dgram');\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, 'localhost', (err) => {\n  client.close();\n});\n
\n

Sending multiple buffers might be faster or slower depending on your\napplication and operating system: benchmark it. Usually it is faster.

\n

A Note about UDP datagram size

\n

The maximum size of an IPv4/v6 datagram depends on the MTU\n(Maximum Transmission Unit) and on the Payload Length field size.

\n\n

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.

\n" }, { "textRaw": "socket.setBroadcast(flag)", "type": "method", "name": "setBroadcast", "meta": { "added": [ "v0.6.9" ] }, "signatures": [ { "params": [ { "textRaw": "`flag` {Boolean} ", "name": "flag", "type": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

Sets or clears the SO_BROADCAST socket option. When set to true, UDP\npackets may be sent to a local interface's broadcast address.

\n" }, { "textRaw": "socket.setMulticastLoopback(flag)", "type": "method", "name": "setMulticastLoopback", "meta": { "added": [ "v0.3.8" ] }, "signatures": [ { "params": [ { "textRaw": "`flag` {Boolean} ", "name": "flag", "type": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

Sets or clears the IP_MULTICAST_LOOP socket option. When set to true,\nmulticast packets will also be received on the local interface.

\n" }, { "textRaw": "socket.setMulticastTTL(ttl)", "type": "method", "name": "setMulticastTTL", "meta": { "added": [ "v0.3.8" ] }, "signatures": [ { "params": [ { "textRaw": "`ttl` {Number} Integer ", "name": "ttl", "type": "Number", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

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.

\n

The argument passed to to socket.setMulticastTTL() is a number of hops\nbetween 0 and 255. The default on most systems is 1 but can vary.

\n" }, { "textRaw": "socket.setTTL(ttl)", "type": "method", "name": "setTTL", "meta": { "added": [ "v0.1.101" ] }, "signatures": [ { "params": [ { "textRaw": "`ttl` {Number} Integer ", "name": "ttl", "type": "Number", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

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.

\n

The argument to socket.setTTL() is a number of hops between 1 and 255.\nThe default on most systems is 64 but can vary.

\n" }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ] }, "desc": "

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.

\n

Calling socket.ref() multiples times will have no additional effect.

\n

The socket.ref() method returns a reference to the socket so calls can be\nchained.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ] }, "desc": "

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.

\n

Calling socket.unref() multiple times will have no addition effect.

\n

The socket.unref() method returns a reference to the socket so calls can be\nchained.

\n", "signatures": [ { "params": [] } ] } ], "modules": [ { "textRaw": "Change to asynchronous `socket.bind()` behavior", "name": "change_to_asynchronous_`socket.bind()`_behavior", "desc": "

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:

\n
const s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');\n
\n

Must be changed to pass a callback function to the dgram.Socket#bind()\nfunction:

\n
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" ] }, "signatures": [ { "return": { "textRaw": "Returns: {dgram.Socket} ", "name": "return", "type": "dgram.Socket" }, "params": [ { "textRaw": "`options` {Object} ", "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} Attached as a listener to `'message'` events. ", "name": "callback", "type": "Function", "desc": "Attached as a listener to `'message'` events.", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "

Creates a dgram.Socket object. The options argument is an object that\nshould contain a type field of either udp4 or udp6 and an optional\nboolean reuseAddr field.

\n

When reuseAddr is true socket.bind() will reuse the address, even if\nanother process has already bound a socket on it. reuseAddr defaults to\nfalse. The optional callback function is added as a listener for 'message'\nevents.

\n

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.

\n" }, { "textRaw": "dgram.createSocket(type[, callback])", "type": "method", "name": "createSocket", "meta": { "added": [ "v0.1.99" ] }, "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. Optional ", "name": "callback", "type": "Function", "optional": true, "desc": "Attached as a listener to `'message'` events." } ] }, { "params": [ { "name": "type" }, { "name": "callback", "optional": true } ] } ], "desc": "

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.

\n

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.

\n" } ], "type": "module", "displayName": "`dgram` module functions" } ], "type": "module", "displayName": "dgram" } ] }