1 # UDP / Datagram Sockets
7 Datagram sockets are available through `require('dgram')`.
9 Important note: the behavior of `dgram.Socket#bind()` has changed in v0.10
10 and is always asynchronous now. If you have code that looks like this:
12 var s = dgram.createSocket('udp4');
14 s.addMembership('224.0.0.114');
16 You have to change it to this:
18 var s = dgram.createSocket('udp4');
19 s.bind(1234, function() {
20 s.addMembership('224.0.0.114');
24 ## dgram.createSocket(type[, callback])
25 ## dgram.createSocket(options[, callback])
27 * `type` String. Either 'udp4' or 'udp6'
28 * `options` Object. Should contain a `type` property and could contain
29 `reuseAddr` property. `false` by default.
30 When `reuseAddr` is `true` - `socket.bind()` will reuse address, even if the
31 other process has already bound a socket on it.
32 * `callback` Function. Attached as a listener to `message` events.
34 * Returns: Socket object
36 Creates a datagram Socket of the specified types. Valid types are `udp4`
39 Takes an optional callback which is added as a listener for `message` events.
41 Call `socket.bind` if you want to receive datagrams. `socket.bind()` will bind
42 to the "all interfaces" address on a random port (it does the right thing for
43 both `udp4` and `udp6` sockets). You can then retrieve the address and port
44 with `socket.address().address` and `socket.address().port`.
46 ## Class: dgram.Socket
48 The dgram Socket class encapsulates the datagram functionality. It
49 should be created via `dgram.createSocket(...)`
53 * `msg` Buffer object. The message
54 * `rinfo` Object. Remote address information
56 Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and
57 `rinfo` is an object with the sender's address information:
59 socket.on('message', function(msg, rinfo) {
60 console.log('Received %d bytes from %s:%d\n',
61 msg.length, rinfo.address, rinfo.port);
64 ### Event: 'listening'
66 Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
71 Emitted when a socket is closed with `close()`. No new `message` events will be emitted
76 * `exception` Error object
78 Emitted when an error occurs.
80 ### socket.send(buf, offset, length, port, address[, callback])
82 * `buf` Buffer object or string. Message to be sent
83 * `offset` Integer. Offset in the buffer where the message starts.
84 * `length` Integer. Number of bytes in the message.
85 * `port` Integer. Destination port.
86 * `address` String. Destination hostname or IP address.
87 * `callback` Function. Called when the message has been sent. Optional.
89 For UDP sockets, the destination port and address must be specified. A string
90 may be supplied for the `address` parameter, and it will be resolved with DNS.
92 If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used
93 instead. Depending on the network configuration, those defaults may or may not
94 work; it's best to be explicit about the destination address.
96 If the socket has not been previously bound with a call to `bind`, it gets
97 assigned a random port number and is bound to the "all interfaces" address
98 (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
100 An optional callback may be specified to detect DNS errors or for determining
101 when it's safe to reuse the `buf` object. Note that DNS lookups delay the time
102 to send for at least one tick. The only way to know for sure that the datagram
103 has been sent is by using a callback.
105 With consideration for multi-byte characters, `offset` and `length` will
106 be calculated with respect to
107 [byte length](buffer.html#buffer_class_method_buffer_bytelength_string_encoding)
108 and not the character position.
110 Example of sending a UDP packet to a random port on `localhost`;
112 var dgram = require('dgram');
113 var message = new Buffer("Some bytes");
114 var client = dgram.createSocket("udp4");
115 client.send(message, 0, message.length, 41234, "localhost", function(err) {
119 **A Note about UDP datagram size**
121 The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_)
122 and on the `Payload Length` field size.
124 - The `Payload Length` field is `16 bits` wide, which means that a normal payload
125 cannot be larger than 64K octets including internet header and data
126 (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
127 this is generally true for loopback interfaces, but such long datagrams
128 are impractical for most hosts and networks.
130 - The `MTU` is the largest size a given link layer technology can support for datagrams.
131 For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU`
132 for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications),
133 whether they arrive whole or in fragments.
135 For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum
136 fragment reassembly buffer size is `1500` octets.
137 The value of `68` octets is very small, since most current link layer technologies have
138 a minimum `MTU` of `1500` (like Ethernet).
140 Note that it's impossible to know in advance the MTU of each link through which
141 a packet might travel, and that generally sending a datagram greater than
142 the (receiver) `MTU` won't work (the packet gets silently dropped, without
143 informing the source that the data did not reach its intended recipient).
145 ### socket.bind(port[, address]\[, callback])
148 * `address` String, Optional
149 * `callback` Function with no parameters, Optional. Callback when
152 For UDP sockets, listen for datagrams on a named `port` and optional
153 `address`. If `address` is not specified, the OS will try to listen on
154 all addresses. After binding is done, a "listening" event is emitted
155 and the `callback`(if specified) is called. Specifying both a
156 "listening" event listener and `callback` is not harmful but not very
159 A bound datagram socket keeps the node process running to receive
162 If binding fails, an "error" event is generated. In rare case (e.g.
163 binding a closed socket), an `Error` may be thrown by this method.
165 Example of a UDP server listening on port 41234:
167 var dgram = require("dgram");
169 var server = dgram.createSocket("udp4");
171 server.on("error", function (err) {
172 console.log("server error:\n" + err.stack);
176 server.on("message", function (msg, rinfo) {
177 console.log("server got: " + msg + " from " +
178 rinfo.address + ":" + rinfo.port);
181 server.on("listening", function () {
182 var address = server.address();
183 console.log("server listening " +
184 address.address + ":" + address.port);
188 // server listening 0.0.0.0:41234
191 ### socket.bind(options[, callback])
193 * `options` {Object} - Required. Supports the following properties:
194 * `port` {Number} - Required.
195 * `address` {String} - Optional.
196 * `exclusive` {Boolean} - Optional.
197 * `callback` {Function} - Optional.
199 The `port` and `address` properties of `options`, as well as the optional
200 callback function, behave as they do on a call to
201 [socket.bind(port, \[address\], \[callback\])
202 ](#dgram_socket_bind_port_address_callback).
204 If `exclusive` is `false` (default), then cluster workers will use the same
205 underlying handle, allowing connection handling duties to be shared. When
206 `exclusive` is `true`, the handle is not shared, and attempted port sharing
207 results in an error. An example which listens on an exclusive port is
211 address: 'localhost',
219 Close the underlying socket and stop listening for data on it.
223 Returns an object containing the address information for a socket. For UDP sockets,
224 this object will contain `address` , `family` and `port`.
226 ### socket.setBroadcast(flag)
230 Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets
231 may be sent to a local interface's broadcast address.
233 ### socket.setTTL(ttl)
237 Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it
238 specifies the number of IP hops that a packet is allowed to go through. Each router or
239 gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
240 router, it will not be forwarded. Changing TTL values is typically done for network
241 probes or when multicasting.
243 The argument to `setTTL()` is a number of hops between 1 and 255. The default on most
246 ### socket.setMulticastTTL(ttl)
250 Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live," but in this
251 context it specifies the number of IP hops that a packet is allowed to go through,
252 specifically for multicast traffic. Each router or gateway that forwards a packet
253 decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
255 The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most
258 ### socket.setMulticastLoopback(flag)
262 Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast
263 packets will also be received on the local interface.
265 ### socket.addMembership(multicastAddress[, multicastInterface])
267 * `multicastAddress` String
268 * `multicastInterface` String, Optional
270 Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option.
272 If `multicastInterface` is not specified, the OS will try to add membership to all valid
275 ### socket.dropMembership(multicastAddress[, multicastInterface])
277 * `multicastAddress` String
278 * `multicastInterface` String, Optional
280 Opposite of `addMembership` - tells the kernel to leave a multicast group with
281 `IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel
282 when the socket is closed or process terminates, so most apps will never need to call
285 If `multicastInterface` is not specified, the OS will try to drop membership to all valid
290 Calling `unref` on a socket will allow the program to exit if this is the only
291 active socket in the event system. If the socket is already `unref`d calling
292 `unref` again will have no effect.
296 Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
297 let the program exit if it's the only socket left (the default behavior). If
298 the socket is `ref`d calling `ref` again will have no effect.