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])
26 * `type` String. Either 'udp4' or 'udp6'
27 * `callback` Function. Attached as a listener to `message` events.
29 * Returns: Socket object
31 Creates a datagram Socket of the specified types. Valid types are `udp4`
34 Takes an optional callback which is added as a listener for `message` events.
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`.
41 ## dgram.createSocket(options[, callback])
43 * `callback` Function. Attached as a listener to `message` events.
44 * Returns: Socket object
46 The `options` object should contain a `type` field of either `udp4` or `udp6`
47 and an optional boolean `reuseAddr` field.
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
53 Takes an optional callback which is added as a listener for `message` events.
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`.
60 ## Class: dgram.Socket
62 The dgram Socket class encapsulates the datagram functionality. It
63 should be created via `dgram.createSocket(...)`
67 * `msg` Buffer object. The message
68 * `rinfo` Object. Remote address information
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:
73 socket.on('message', function(msg, rinfo) {
74 console.log('Received %d bytes from %s:%d\n',
75 msg.length, rinfo.address, rinfo.port);
78 ### Event: 'listening'
80 Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
85 Emitted after a socket is closed with `close()`. No new `message` events will be emitted
90 * `exception` Error object
92 Emitted when an error occurs.
94 ### socket.send(buf, offset, length, port, address[, callback])
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.
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.
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.
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.)
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.
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.
126 Example of sending a UDP packet to a random port on `localhost`;
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) {
135 **A Note about UDP datagram size**
137 The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_)
138 and on the `Payload Length` field size.
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.
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.
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).
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).
161 ### socket.bind([port][, address][, callback])
163 * `port` Integer, Optional
164 * `address` String, Optional
165 * `callback` Function with no parameters, Optional. Callback when
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
176 A bound datagram socket keeps the Node.js process running to receive
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.
182 Example of a UDP server listening on port 41234:
184 var dgram = require("dgram");
186 var server = dgram.createSocket("udp4");
188 server.on("error", function (err) {
189 console.log("server error:\n" + err.stack);
193 server.on("message", function (msg, rinfo) {
194 console.log("server got: " + msg + " from " +
195 rinfo.address + ":" + rinfo.port);
198 server.on("listening", function () {
199 var address = server.address();
200 console.log("server listening " +
201 address.address + ":" + address.port);
205 // server listening 0.0.0.0:41234
208 ### socket.bind(options[, callback])
210 * `options` {Object} - Required. Supports the following properties:
211 * `port` {Number} - Required.
212 * `address` {String} - Optional.
213 * `exclusive` {Boolean} - Optional.
214 * `callback` {Function} - Optional.
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).
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
228 address: 'localhost',
234 ### socket.close([callback])
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.
241 Returns an object containing the address information for a socket. For UDP sockets,
242 this object will contain `address` , `family` and `port`.
244 ### socket.setBroadcast(flag)
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.
251 ### socket.setTTL(ttl)
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.
261 The argument to `setTTL()` is a number of hops between 1 and 255. The default on most
264 ### socket.setMulticastTTL(ttl)
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.
273 The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most
276 ### socket.setMulticastLoopback(flag)
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.
283 ### socket.addMembership(multicastAddress[, multicastInterface])
285 * `multicastAddress` String
286 * `multicastInterface` String, Optional
288 Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option.
290 If `multicastInterface` is not specified, the OS will try to add membership to all valid
293 ### socket.dropMembership(multicastAddress[, multicastInterface])
295 * `multicastAddress` String
296 * `multicastInterface` String, Optional
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
303 If `multicastInterface` is not specified, the OS will try to drop membership to all valid
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.
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.