doc: remove "above" and "below" references
[platform/upstream/nodejs.git] / doc / api / dgram.markdown
1 # UDP / Datagram Sockets
2
3     Stability: 2 - Stable
4
5 <!-- name=dgram -->
6
7 The `dgram` module provides an implementation of UDP Datagram sockets.
8
9     const dgram = require('dgram');
10     const server = dgram.createSocket('udp4');
11
12     server.on('error', (err) => {
13       console.log(`server error:\n${err.stack}`);
14       server.close();
15     });
16
17     server.on('message', (msg, rinfo) => {
18       console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
19     });
20
21     server.on('listening', () => {
22       var address = server.address();
23       console.log(`server listening ${address.address}:${address.port}`);
24     });
25
26     server.bind(41234);
27     // server listening 0.0.0.0:41234
28
29 ## Class: dgram.Socket
30
31 The `dgram.Socket` object is an [`EventEmitter`][] that encapsulates the
32 datagram functionality.
33
34 New instances of `dgram.Socket` are created using [`dgram.createSocket()`][].
35 The `new` keyword is not to be used to create `dgram.Socket` instances.
36
37 ### Event: 'close'
38
39 The `'close'` event is emitted after a socket is closed with [`close()`][].
40 Once triggered, no new `'message'` events will be emitted on this socket.
41
42 ### Event: 'error'
43
44 * `exception` Error object
45
46 The `'error'` event is emitted whenever any error occurs. The event handler
47 function is passed a single Error object.
48
49 ### Event: 'listening'
50
51 The `'listening'` event is emitted whenever a socket begins listening for
52 datagram messages. This occurs as soon as UDP sockets are created.
53
54 ### Event: 'message'
55
56 * `msg` Buffer object. The message
57 * `rinfo` Object. Remote address information
58
59 The `'message'` event is emitted when a new datagram is available on a socket.
60 The event handler function is passed two arguments: `msg` and `rinfo`. The
61 `msg` argument is a [`Buffer`][] and `rinfo` is an object with the sender's
62 address information provided by the `address`, `family` and `port` properties:
63
64     socket.on('message', (msg, rinfo) => {
65       console.log('Received %d bytes from %s:%d\n',
66                   msg.length, rinfo.address, rinfo.port);
67     });
68
69 ### socket.addMembership(multicastAddress[, multicastInterface])
70
71 * `multicastAddress` String
72 * `multicastInterface` String, Optional
73
74 Tells the kernel to join a multicast group at the given `multicastAddress`
75 using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface`
76 argument is not specified, the operating system will try to add membership to
77 all valid networking interfaces.
78
79 ### socket.address()
80
81 Returns an object containing the address information for a socket.
82 For UDP sockets, this object will contain `address`, `family` and `port`
83 properties.
84
85 ### socket.bind([port][, address][, callback])
86
87 * `port` Integer, Optional
88 * `address` String, Optional
89 * `callback` Function with no parameters, Optional. Called when
90   binding is complete.
91
92 For UDP sockets, causes the `dgram.Socket` to listen for datagram messages on a
93 named `port` and optional `address`. If `port` is not specified, the operating
94 system will attempt to bind to a random port. If `address` is not specified,
95 the operating system will attempt to listen on all addresses.  Once binding is
96 complete, a `'listening'` event is emitted and the optional `callback` function
97 is called.
98
99 Note that specifying both a `'listening'` event listener and passing a
100 `callback` to the `socket.bind()` method is not harmful but not very
101 useful.
102
103 A bound datagram socket keeps the Node.js process running to receive
104 datagram messages.
105
106 If binding fails, an `'error'` event is generated. In rare case (e.g.
107 attempting to bind with a closed socket), an [`Error`][] may be thrown.
108
109 Example of a UDP server listening on port 41234:
110
111     const dgram = require('dgram');
112     const server = dgram.createSocket('udp4');
113
114     server.on('error', (err) => {
115       console.log(`server error:\n${err.stack}`);
116       server.close();
117     });
118
119     server.on('message', (msg, rinfo) => {
120       console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
121     });
122
123     server.on('listening', () => {
124       var address = server.address();
125       console.log(`server listening ${address.address}:${address.port}`);
126     });
127
128     server.bind(41234);
129     // server listening 0.0.0.0:41234
130
131 ### socket.bind(options[, callback])
132
133 * `options` {Object} - Required. Supports the following properties:
134   * `port` {Number} - Required.
135   * `address` {String} - Optional.
136   * `exclusive` {Boolean} - Optional.
137 * `callback` {Function} - Optional.
138
139 For UDP sockets, causes the `dgram.Socket` to listen for datagram messages on a
140 named `port` and optional `address` that are passed as properties of an
141 `options` object passed as the first argument. If `port` is not specified, the
142 operating system will attempt to bind to a random port. If `address` is not
143 specified, the operating system will attempt to listen on all addresses.  Once
144 binding is complete, a `'listening'` event is emitted and the optional
145 `callback` function is called.
146
147 The `options` object may contain an additional `exclusive` property that is
148 use when using `dgram.Socket` objects with the [`cluster`] module. When
149 `exclusive` is set to `false` (the default), cluster workers will use the same
150 underlying socket handle allowing connection handling duties to be shared.
151 When `exclusive` is `true`, however, the handle is not shared and attempted
152 port sharing results in an error.
153
154 An example socket listening on an exclusive port is shown below.
155
156     socket.bind({
157       address: 'localhost',
158       port: 8000,
159       exclusive: true
160     });
161
162 ### socket.close([callback])
163
164 Close the underlying socket and stop listening for data on it. If a callback is
165 provided, it is added as a listener for the [`'close'`][] event.
166
167 ### socket.dropMembership(multicastAddress[, multicastInterface])
168
169 * `multicastAddress` String
170 * `multicastInterface` String, Optional
171
172 Instructs the kernel to leave a multicast group at `multicastAddress` using the
173 `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
174 kernel when the socket is closed or the process terminates, so most apps will
175 never have reason to call this.
176
177 If `multicastInterface` is not specified, the operating system will attempt to
178 drop membership on all valid interfaces.
179
180 ### socket.send(buf, offset, length, port, address[, callback])
181
182 * `buf` Buffer object or string.  Message to be sent
183 * `offset` Integer. Offset in the buffer where the message starts.
184 * `length` Integer. Number of bytes in the message.
185 * `port` Integer. Destination port.
186 * `address` String. Destination hostname or IP address.
187 * `callback` Function. Called when the message has been sent. Optional.
188
189 Broadcasts a datagram on the socket. The destination `port` and `address` must
190 be specified.
191
192 The `buf` argument is a [`Buffer`] object containing the message. The `offset`
193 and `length` specify the offset within the `Buffer` where the message begins
194 and the number of bytes in the message, respectively. With messages that
195 contain  multi-byte characters, `offset` and `length` will be calculated with
196 respect to [byte length][] and not the character position.
197
198 The `address` argument is a string. If the value of `address` is a host name,
199 DNS will be used to resolve the address of the host. If the `address` is not
200 specified or is an empty string, `'0.0.0.0'` or `'::0'` will be used instead.
201 It is possible, depending on the network configuration, that these defaults
202 may not work; accordingly, it is best to be explicit about the destination
203 address.
204
205 If the socket has not been previously bound with a call to `bind`, the socket
206 is assigned a random port number and is bound to the "all interfaces" address
207 (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
208
209 An optional `callback` function  may be specified to as a way of reporting
210 DNS errors or for determining when it is safe to reuse the `buf` object.
211 Note that DNS lookups delay the time to send for at least one tick of the
212 Node.js event loop.
213
214 The only way to know for sure that the datagram has been sent is by using a
215 `callback`. If an error occurs and a `callback` is given, the error will be
216 passed as the first argument to the `callback`. If a `callback` is not given,
217 the error is emitted as an `'error'` event on the `socket` object.
218
219 Example of sending a UDP packet to a random port on `localhost`;
220
221     const dgram = require('dgram');
222     const message = new Buffer('Some bytes');
223     const client = dgram.createSocket('udp4');
224     client.send(message, 0, message.length, 41234, 'localhost', (err) => {
225       client.close();
226     });
227
228 **A Note about UDP datagram size**
229
230 The maximum size of an `IPv4/v6` datagram depends on the `MTU`
231 (_Maximum Transmission Unit_) and on the `Payload Length` field size.
232
233 - The `Payload Length` field is `16 bits` wide, which means that a normal
234   payload exceed 64K octets _including_ the internet header and data
235   (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
236   this is generally true for loopback interfaces, but such long datagram
237   messages are impractical for most hosts and networks.
238
239 - The `MTU` is the largest size a given link layer technology can support for
240   datagram messages. For any link, `IPv4` mandates a minimum `MTU` of `68`
241   octets, while the recommended `MTU` for IPv4 is `576` (typically recommended
242   as the `MTU` for dial-up type applications), whether they arrive whole or in
243   fragments.
244
245   For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum
246   fragment reassembly buffer size is `1500` octets. The value of `68` octets is
247   very small, since most current link layer technologies, like Ethernet, have a
248   minimum `MTU` of `1500`.
249
250 It is impossible to know in advance the MTU of each link through which
251 a packet might travel. Sending a datagram greater than the receiver `MTU` will
252 not work because the packet will get silently dropped without informing the
253 source that the data did not reach its intended recipient.
254
255 ### socket.setBroadcast(flag)
256
257 * `flag` Boolean
258
259 Sets or clears the `SO_BROADCAST` socket option.  When set to `true`, UDP
260 packets may be sent to a local interface's broadcast address.
261
262 ### socket.setMulticastLoopback(flag)
263
264 * `flag` Boolean
265
266 Sets or clears the `IP_MULTICAST_LOOP` socket option.  When set to `true`,
267 multicast packets will also be received on the local interface.
268
269 ### socket.setMulticastTTL(ttl)
270
271 * `ttl` Integer
272
273 Sets the `IP_MULTICAST_TTL` socket option.  While TTL generally stands for
274 "Time to Live", in this context it specifies the number of IP hops that a
275 packet is allowed to travel through, specifically for multicast traffic.  Each
276 router or gateway that forwards a packet decrements the TTL. If the TTL is
277 decremented to 0 by a router, it will not be forwarded.
278
279 The argument passed to to `socket.setMulticastTTL()` is a number of hops
280 between 0 and 255. The default on most systems is `1` but can vary.
281
282 ### socket.setTTL(ttl)
283
284 * `ttl` Integer
285
286 Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
287 in this context it specifies the number of IP hops that a packet is allowed to
288 travel through.  Each router or gateway that forwards a packet decrements the
289 TTL.  If the TTL is decremented to 0 by a router, it will not be forwarded.
290 Changing TTL values is typically done for network probes or when multicasting.
291
292 The argument to `socket.setTTL()` is a number of hops between 1 and 255.
293 The default on most systems is 64 but can vary.
294
295 ### socket.ref()
296
297 By default, binding a socket will cause it to block the Node.js process from
298 exiting as long as the socket is open. The `socket.unref()` method can be used
299 to exclude the socket from the reference counting that keeps the Node.js
300 process active. The `socket.ref()` method adds the socket back to the reference
301 counting and restores the default behavior.
302
303 Calling `socket.ref()` multiples times will have no additional effect.
304
305 The `socket.ref()` method returns a reference to the socket so calls can be
306 chained.
307
308 ### socket.unref()
309
310 By default, binding a socket will cause it to block the Node.js process from
311 exiting as long as the socket is open. The `socket.unref()` method can be used
312 to exclude the socket from the reference counting that keeps the Node.js
313 process active, allowing the process to exit even if the socket is still
314 listening.
315
316 Calling `socket.unref()` multiple times will have no addition effect.
317
318 The `socket.unref()` method returns a reference to the socket so calls can be
319 chained.
320
321 ### Change to asynchronous `socket.bind()` behavior
322
323 As of Node.js v0.10, [`dgram.Socket#bind()`][] changed to an asynchronous
324 execution model. Legacy code that assumes synchronous behavior, as in the
325 following example:
326
327     const s = dgram.createSocket('udp4');
328     s.bind(1234);
329     s.addMembership('224.0.0.114');
330
331 Must be changed to pass a callback function to the [`dgram.Socket#bind()`][]
332 function:
333
334     const s = dgram.createSocket('udp4');
335     s.bind(1234, () => {
336       s.addMembership('224.0.0.114');
337     });
338
339 ## `dgram` module functions
340
341 ### dgram.createSocket(options[, callback])
342
343 * `options` Object
344 * `callback` Function. Attached as a listener to `'message'` events.
345 * Returns: Socket object
346
347 Creates a `dgram.Socket` object. The `options` argument is an object that
348 should contain a `type` field of either `udp4` or `udp6` and an optional
349 boolean `reuseAddr` field.
350
351 When `reuseAddr` is `true` [`socket.bind()`][] will reuse the address, even if
352 another process has already bound a socket on it. `reuseAddr` defaults to
353 `false`. An optional `callback` function can be passed specified which is added
354 as a listener for `'message'` events.
355
356 Once the socket is created, calling [`socket.bind()`][] will instruct the
357 socket to begin listening for datagram messages. When `address` and `port` are
358 not passed to  [`socket.bind()`][] the method will bind the socket to the "all
359 interfaces" address on a random port (it does the right thing for both `udp4`
360 and `udp6` sockets). The bound address and port can be retrieved using
361 [`socket.address().address`][] and [`socket.address().port`][].
362
363 ### dgram.createSocket(type[, callback])
364
365 * `type` String. Either 'udp4' or 'udp6'
366 * `callback` Function. Attached as a listener to `'message'` events.
367   Optional
368 * Returns: Socket object
369
370 Creates a `dgram.Socket` object of the specified `type`. The `type` argument
371 can be either `udp4` or `udp6`. An optional `callback` function can be passed
372 which is added as a listener for `'message'` events.
373
374 Once the socket is created, calling [`socket.bind()`][] will instruct the
375 socket to begin listening for datagram messages. When `address` and `port` are
376 not passed to  [`socket.bind()`][] the method will bind the socket to the "all
377 interfaces" address on a random port (it does the right thing for both `udp4`
378 and `udp6` sockets). The bound address and port can be retrieved using
379 [`socket.address().address`][] and [`socket.address().port`][].
380
381 [`EventEmitter`]: events.html
382 [`Buffer`]: buffer.html
383 [`'close'`]: #dgram_event_close
384 [`addMembership()`]: #dgram_socket_addmembership_multicastaddress_multicastinterface
385 [`close()`]: #dgram_socket_close_callback
386 [`dgram.createSocket()`]: #dgram_dgram_createsocket_options_callback
387 [`dgram.Socket#bind()`]: #dgram_socket_bind_options_callback
388 [`Error`]: errors.html#errors_class_error
389 [`socket.address().address`]: #dgram_socket_address
390 [`socket.address().port`]: #dgram_socket_address
391 [`socket.bind()`]: #dgram_socket_bind_port_address_callback
392 [byte length]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding