doc: port is optional for socket.bind()
[platform/upstream/nodejs.git] / doc / api / dgram.markdown
1 # UDP / Datagram Sockets
2
3     Stability: 2 - Stable
4
5 <!-- name=dgram -->
6
7 Datagram sockets are available through `require('dgram')`.
8
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:
11
12     var s = dgram.createSocket('udp4');
13     s.bind(1234);
14     s.addMembership('224.0.0.114');
15
16 You have to change it to this:
17
18     var s = dgram.createSocket('udp4');
19     s.bind(1234, function() {
20       s.addMembership('224.0.0.114');
21     });
22
23
24 ## dgram.createSocket(type[, callback])
25
26 * `type` String. Either 'udp4' or 'udp6'
27 * `callback` Function. Attached as a listener to `message` events.
28   Optional
29 * Returns: Socket object
30
31 Creates a datagram Socket of the specified types.  Valid types are `udp4`
32 and `udp6`.
33
34 Takes an optional callback which is added as a listener for `message` events.
35
36 Call `socket.bind()` if you want to receive datagrams. `socket.bind()` will
37 bind to the "all interfaces" address on a random port (it does the right thing
38 for both `udp4` and `udp6` sockets). You can then retrieve the address and port
39 with `socket.address().address` and `socket.address().port`.
40
41 ## dgram.createSocket(options[, callback])
42 * `options` Object
43 * `callback` Function. Attached as a listener to `message` events.
44 * Returns: Socket object
45
46 The `options` object should contain a `type` field of either `udp4` or `udp6`
47 and an optional boolean `reuseAddr` field.
48
49 When `reuseAddr` is `true` `socket.bind()` will reuse the address, even if
50 another process has already bound a socket on it. `reuseAddr` defaults to
51 `false`.
52
53 Takes an optional callback which is added as a listener for `message` events.
54
55 Call `socket.bind()` if you want to receive datagrams. `socket.bind()` will
56 bind to the "all interfaces" address on a random port (it does the right thing
57 for both `udp4` and `udp6` sockets). You can then retrieve the address and port
58 with `socket.address().address` and `socket.address().port`.
59
60 ## Class: dgram.Socket
61
62 The dgram Socket class encapsulates the datagram functionality.  It
63 should be created via `dgram.createSocket(...)`
64
65 ### Event: 'message'
66
67 * `msg` Buffer object. The message
68 * `rinfo` Object. Remote address information
69
70 Emitted when a new datagram is available on a socket.  `msg` is a `Buffer` and
71 `rinfo` is an object with the sender's address information:
72
73     socket.on('message', function(msg, rinfo) {
74       console.log('Received %d bytes from %s:%d\n',
75                   msg.length, rinfo.address, rinfo.port);
76     });
77
78 ### Event: 'listening'
79
80 Emitted when a socket starts listening for datagrams.  This happens as soon as UDP sockets
81 are created.
82
83 ### Event: 'close'
84
85 Emitted after a socket is closed with `close()`.  No new `message` events will be emitted
86 on this socket.
87
88 ### Event: 'error'
89
90 * `exception` Error object
91
92 Emitted when an error occurs.
93
94 ### socket.send(buf, offset, length, port, address[, callback])
95
96 * `buf` Buffer object or string.  Message to be sent
97 * `offset` Integer. Offset in the buffer where the message starts.
98 * `length` Integer. Number of bytes in the message.
99 * `port` Integer. Destination port.
100 * `address` String. Destination hostname or IP address.
101 * `callback` Function. Called when the message has been sent. Optional.
102
103 For UDP sockets, the destination port and address must be specified.  A string
104 may be supplied for the `address` parameter, and it will be resolved with DNS.
105
106 If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used
107 instead.  Depending on the network configuration, those defaults may or may not
108 work; it's best to be explicit about the destination address.
109
110 If the socket has not been previously bound with a call to `bind`, it gets
111 assigned a random port number and is bound to the "all interfaces" address
112 (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
113
114 An optional callback may be specified to detect DNS errors or for determining
115 when it's safe to reuse the `buf` object.  Note that DNS lookups delay the time
116 to send for at least one tick.  The only way to know for sure that the datagram
117 has been sent is by using a callback. If an error occurs and a callback is
118 given, the error will be the first argument to the callback. If a callback is
119 not given, the error is emitted as an `'error'` event on the `socket` object.
120
121 With consideration for multi-byte characters, `offset` and `length` will
122 be calculated with respect to
123 [byte length](buffer.html#buffer_class_method_buffer_bytelength_string_encoding)
124 and not the character position.
125
126 Example of sending a UDP packet to a random port on `localhost`;
127
128     var dgram = require('dgram');
129     var message = new Buffer("Some bytes");
130     var client = dgram.createSocket("udp4");
131     client.send(message, 0, message.length, 41234, "localhost", function(err) {
132       client.close();
133     });
134
135 **A Note about UDP datagram size**
136
137 The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_)
138 and on the `Payload Length` field size.
139
140 - The `Payload Length` field is `16 bits` wide, which means that a normal payload
141   cannot be larger than 64K octets including internet header and data
142   (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
143   this is generally true for loopback interfaces, but such long datagrams
144   are impractical for most hosts and networks.
145
146 - The `MTU` is the largest size a given link layer technology can support for datagrams.
147   For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU`
148   for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications),
149   whether they arrive whole or in fragments.
150
151   For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum
152   fragment reassembly buffer size is `1500` octets.
153   The value of `68` octets is very small, since most current link layer technologies have
154   a minimum `MTU` of `1500` (like Ethernet).
155
156 Note that it's impossible to know in advance the MTU of each link through which
157 a packet might travel, and that generally sending a datagram greater than
158 the (receiver) `MTU` won't work (the packet gets silently dropped, without
159 informing the source that the data did not reach its intended recipient).
160
161 ### socket.bind([port][, address][, callback])
162
163 * `port` Integer, Optional
164 * `address` String, Optional
165 * `callback` Function with no parameters, Optional. Callback when
166   binding is done.
167
168 For UDP sockets, listen for datagrams on a named `port` and optional
169 `address`. If `port` is not specified, the OS will try to bind to a random
170 port. If `address` is not specified, the OS will try to listen on
171 all addresses.  After binding is done, a "listening" event is emitted
172 and the `callback`(if specified) is called. Specifying both a
173 "listening" event listener and `callback` is not harmful but not very
174 useful.
175
176 A bound datagram socket keeps the Node.js process running to receive
177 datagrams.
178
179 If binding fails, an "error" event is generated. In rare case (e.g.
180 binding a closed socket), an `Error` may be thrown by this method.
181
182 Example of a UDP server listening on port 41234:
183
184     var dgram = require("dgram");
185
186     var server = dgram.createSocket("udp4");
187
188     server.on("error", function (err) {
189       console.log("server error:\n" + err.stack);
190       server.close();
191     });
192
193     server.on("message", function (msg, rinfo) {
194       console.log("server got: " + msg + " from " +
195         rinfo.address + ":" + rinfo.port);
196     });
197
198     server.on("listening", function () {
199       var address = server.address();
200       console.log("server listening " +
201           address.address + ":" + address.port);
202     });
203
204     server.bind(41234);
205     // server listening 0.0.0.0:41234
206
207
208 ### socket.bind(options[, callback])
209
210 * `options` {Object} - Required. Supports the following properties:
211   * `port` {Number} - Required.
212   * `address` {String} - Optional.
213   * `exclusive` {Boolean} - Optional.
214 * `callback` {Function} - Optional.
215
216 The `port` and `address` properties of `options`, as well as the optional
217 callback function, behave as they do on a call to
218 [socket.bind(port, \[address\], \[callback\])
219 ](#dgram_socket_bind_port_address_callback).
220
221 If `exclusive` is `false` (default), then cluster workers will use the same
222 underlying handle, allowing connection handling duties to be shared. When
223 `exclusive` is `true`, the handle is not shared, and attempted port sharing
224 results in an error. An example which listens on an exclusive port is
225 shown below.
226
227     socket.bind({
228       address: 'localhost',
229       port: 8000,
230       exclusive: true
231     });
232
233
234 ### socket.close([callback])
235
236 Close the underlying socket and stop listening for data on it. If a callback is
237 provided, it is added as a listener for the ['close'](#dgram_event_close) event.
238
239 ### socket.address()
240
241 Returns an object containing the address information for a socket.  For UDP sockets,
242 this object will contain `address` , `family` and `port`.
243
244 ### socket.setBroadcast(flag)
245
246 * `flag` Boolean
247
248 Sets or clears the `SO_BROADCAST` socket option.  When this option is set, UDP packets
249 may be sent to a local interface's broadcast address.
250
251 ### socket.setTTL(ttl)
252
253 * `ttl` Integer
254
255 Sets the `IP_TTL` socket option.  TTL stands for "Time to Live," but in this context it
256 specifies the number of IP hops that a packet is allowed to go through.  Each router or
257 gateway that forwards a packet decrements the TTL.  If the TTL is decremented to 0 by a
258 router, it will not be forwarded.  Changing TTL values is typically done for network
259 probes or when multicasting.
260
261 The argument to `setTTL()` is a number of hops between 1 and 255.  The default on most
262 systems is 64.
263
264 ### socket.setMulticastTTL(ttl)
265
266 * `ttl` Integer
267
268 Sets the `IP_MULTICAST_TTL` socket option.  TTL stands for "Time to Live," but in this
269 context it specifies the number of IP hops that a packet is allowed to go through,
270 specifically for multicast traffic.  Each router or gateway that forwards a packet
271 decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
272
273 The argument to `setMulticastTTL()` is a number of hops between 0 and 255.  The default on most
274 systems is 1.
275
276 ### socket.setMulticastLoopback(flag)
277
278 * `flag` Boolean
279
280 Sets or clears the `IP_MULTICAST_LOOP` socket option.  When this option is set, multicast
281 packets will also be received on the local interface.
282
283 ### socket.addMembership(multicastAddress[, multicastInterface])
284
285 * `multicastAddress` String
286 * `multicastInterface` String, Optional
287
288 Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option.
289
290 If `multicastInterface` is not specified, the OS will try to add membership to all valid
291 interfaces.
292
293 ### socket.dropMembership(multicastAddress[, multicastInterface])
294
295 * `multicastAddress` String
296 * `multicastInterface` String, Optional
297
298 Opposite of `addMembership` - tells the kernel to leave a multicast group with
299 `IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel
300 when the socket is closed or process terminates, so most apps will never need to call
301 this.
302
303 If `multicastInterface` is not specified, the OS will try to drop membership to all valid
304 interfaces.
305
306 ### socket.unref()
307
308 Calling `unref` on a socket will allow the program to exit if this is the only
309 active socket in the event system. If the socket is already `unref`d calling
310 `unref` again will have no effect.
311
312 Returns `socket`.
313
314 ### socket.ref()
315
316 Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
317 let the program exit if it's the only socket left (the default behavior). If
318 the socket is `ref`d calling `ref` again will have no effect.
319
320 Returns `socket`.