• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v14.19.1">
7  <title>UDP/datagram sockets | Node.js v14.19.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/dgram.html">
12</head>
13<body class="alt apidoc" id="api-section-dgram">
14  <div id="content" class="clearfix">
15    <div id="column2" class="interior">
16      <div id="intro" class="interior">
17        <a href="/" title="Go back to the home page">
18          Node.js
19        </a>
20      </div>
21      <ul>
22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
24</ul>
25<hr class="line">
26<ul>
27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
30<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
35<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
36<li><a href="console.html" class="nav-console">Console</a></li>
37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
42<li><a href="dns.html" class="nav-dns">DNS</a></li>
43<li><a href="domain.html" class="nav-domain">Domain</a></li>
44<li><a href="errors.html" class="nav-errors">Errors</a></li>
45<li><a href="events.html" class="nav-events">Events</a></li>
46<li><a href="fs.html" class="nav-fs">File system</a></li>
47<li><a href="globals.html" class="nav-globals">Globals</a></li>
48<li><a href="http.html" class="nav-http">HTTP</a></li>
49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
50<li><a href="https.html" class="nav-https">HTTPS</a></li>
51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
52<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li>
56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
57<li><a href="net.html" class="nav-net">Net</a></li>
58<li><a href="os.html" class="nav-os">OS</a></li>
59<li><a href="path.html" class="nav-path">Path</a></li>
60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
61<li><a href="policy.html" class="nav-policy">Policies</a></li>
62<li><a href="process.html" class="nav-process">Process</a></li>
63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
65<li><a href="readline.html" class="nav-readline">Readline</a></li>
66<li><a href="repl.html" class="nav-repl">REPL</a></li>
67<li><a href="report.html" class="nav-report">Report</a></li>
68<li><a href="stream.html" class="nav-stream">Stream</a></li>
69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
70<li><a href="timers.html" class="nav-timers">Timers</a></li>
71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
73<li><a href="tty.html" class="nav-tty">TTY</a></li>
74<li><a href="dgram.html" class="nav-dgram active">UDP/datagram</a></li>
75<li><a href="url.html" class="nav-url">URL</a></li>
76<li><a href="util.html" class="nav-util">Utilities</a></li>
77<li><a href="v8.html" class="nav-v8">V8</a></li>
78<li><a href="vm.html" class="nav-vm">VM</a></li>
79<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
82</ul>
83<hr class="line">
84<ul>
85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
86</ul>
87    </div>
88
89    <div id="column1" data-id="dgram" class="interior">
90      <header>
91        <div class="header-container">
92          <h1>Node.js v14.19.1 documentation</h1>
93          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
94            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
95              <path fill="none" d="M0 0h24v24H0z" />
96              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
97              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
98            </svg>
99            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
100              <path d="M0 0h24v24H0z" fill="none" />
101              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
102            </svg>
103          </button>
104        </div>
105        <div id="gtoc">
106          <ul>
107            <li>
108              <a href="index.html">Index</a>
109            </li>
110            <li>
111              <a href="all.html">View on single page</a>
112            </li>
113            <li>
114              <a href="dgram.json">View as JSON</a>
115            </li>
116
117    <li class="version-picker">
118      <a href="#">View another version <span>&#x25bc;</span></a>
119      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v17.x/api/dgram.html">17.x</a></li>
120<li><a href="https://nodejs.org/docs/latest-v16.x/api/dgram.html">16.x <b>LTS</b></a></li>
121<li><a href="https://nodejs.org/docs/latest-v15.x/api/dgram.html">15.x</a></li>
122<li><a href="https://nodejs.org/docs/latest-v14.x/api/dgram.html">14.x <b>LTS</b></a></li>
123<li><a href="https://nodejs.org/docs/latest-v13.x/api/dgram.html">13.x</a></li>
124<li><a href="https://nodejs.org/docs/latest-v12.x/api/dgram.html">12.x <b>LTS</b></a></li>
125<li><a href="https://nodejs.org/docs/latest-v11.x/api/dgram.html">11.x</a></li>
126<li><a href="https://nodejs.org/docs/latest-v10.x/api/dgram.html">10.x</a></li>
127<li><a href="https://nodejs.org/docs/latest-v9.x/api/dgram.html">9.x</a></li>
128<li><a href="https://nodejs.org/docs/latest-v8.x/api/dgram.html">8.x</a></li>
129<li><a href="https://nodejs.org/docs/latest-v7.x/api/dgram.html">7.x</a></li>
130<li><a href="https://nodejs.org/docs/latest-v6.x/api/dgram.html">6.x</a></li>
131<li><a href="https://nodejs.org/docs/latest-v5.x/api/dgram.html">5.x</a></li>
132<li><a href="https://nodejs.org/docs/latest-v4.x/api/dgram.html">4.x</a></li>
133<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/dgram.html">0.12.x</a></li>
134<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/dgram.html">0.10.x</a></li></ol>
135    </li>
136
137            <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/dgram.md">Edit on GitHub</a></li>
138          </ul>
139        </div>
140        <hr>
141      </header>
142
143      <details id="toc" open><summary>Table of contents</summary><ul>
144<li><span class="stability_2"><a href="#dgram_udp_datagram_sockets">UDP/datagram sockets</a></span>
145<ul>
146<li><a href="#dgram_class_dgram_socket">Class: <code>dgram.Socket</code></a>
147<ul>
148<li><a href="#dgram_event_close">Event: <code>'close'</code></a></li>
149<li><a href="#dgram_event_connect">Event: <code>'connect'</code></a></li>
150<li><a href="#dgram_event_error">Event: <code>'error'</code></a></li>
151<li><a href="#dgram_event_listening">Event: <code>'listening'</code></a></li>
152<li><a href="#dgram_event_message">Event: <code>'message'</code></a></li>
153<li><a href="#dgram_socket_addmembership_multicastaddress_multicastinterface"><code>socket.addMembership(multicastAddress[, multicastInterface])</code></a></li>
154<li><a href="#dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
155<li><a href="#dgram_socket_address"><code>socket.address()</code></a></li>
156<li><a href="#dgram_socket_bind_port_address_callback"><code>socket.bind([port][, address][, callback])</code></a></li>
157<li><a href="#dgram_socket_bind_options_callback"><code>socket.bind(options[, callback])</code></a></li>
158<li><a href="#dgram_socket_close_callback"><code>socket.close([callback])</code></a></li>
159<li><a href="#dgram_socket_connect_port_address_callback"><code>socket.connect(port[, address][, callback])</code></a></li>
160<li><a href="#dgram_socket_disconnect"><code>socket.disconnect()</code></a></li>
161<li><a href="#dgram_socket_dropmembership_multicastaddress_multicastinterface"><code>socket.dropMembership(multicastAddress[, multicastInterface])</code></a></li>
162<li><a href="#dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
163<li><a href="#dgram_socket_getrecvbuffersize"><code>socket.getRecvBufferSize()</code></a></li>
164<li><a href="#dgram_socket_getsendbuffersize"><code>socket.getSendBufferSize()</code></a></li>
165<li><a href="#dgram_socket_ref"><code>socket.ref()</code></a></li>
166<li><a href="#dgram_socket_remoteaddress"><code>socket.remoteAddress()</code></a></li>
167<li><a href="#dgram_socket_send_msg_offset_length_port_address_callback"><code>socket.send(msg[, offset, length][, port][, address][, callback])</code></a>
168<ul>
169<li><a href="#dgram_note_about_udp_datagram_size">Note about UDP datagram size</a></li>
170</ul>
171</li>
172<li><a href="#dgram_socket_setbroadcast_flag"><code>socket.setBroadcast(flag)</code></a></li>
173<li><a href="#dgram_socket_setmulticastinterface_multicastinterface"><code>socket.setMulticastInterface(multicastInterface)</code></a>
174<ul>
175<li><a href="#dgram_example_ipv6_outgoing_multicast_interface">Example: IPv6 outgoing multicast interface</a></li>
176<li><a href="#dgram_example_ipv4_outgoing_multicast_interface">Example: IPv4 outgoing multicast interface</a></li>
177<li><a href="#dgram_call_results">Call results</a></li>
178</ul>
179</li>
180<li><a href="#dgram_socket_setmulticastloopback_flag"><code>socket.setMulticastLoopback(flag)</code></a></li>
181<li><a href="#dgram_socket_setmulticastttl_ttl"><code>socket.setMulticastTTL(ttl)</code></a></li>
182<li><a href="#dgram_socket_setrecvbuffersize_size"><code>socket.setRecvBufferSize(size)</code></a></li>
183<li><a href="#dgram_socket_setsendbuffersize_size"><code>socket.setSendBufferSize(size)</code></a></li>
184<li><a href="#dgram_socket_setttl_ttl"><code>socket.setTTL(ttl)</code></a></li>
185<li><a href="#dgram_socket_unref"><code>socket.unref()</code></a></li>
186</ul>
187</li>
188<li><a href="#dgram_dgram_module_functions"><code>dgram</code> module functions</a>
189<ul>
190<li><a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket(options[, callback])</code></a></li>
191<li><a href="#dgram_dgram_createsocket_type_callback"><code>dgram.createSocket(type[, callback])</code></a></li>
192</ul>
193</li>
194</ul>
195</li>
196</ul></details>
197
198      <div id="apicontent">
199        <h2>UDP/datagram sockets<span><a class="mark" href="#dgram_udp_datagram_sockets" id="dgram_udp_datagram_sockets">#</a></span></h2>
200
201<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
202
203<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v14.19.1/lib/dgram.js">lib/dgram.js</a></p>
204<p>The <code>dgram</code> module provides an implementation of UDP datagram sockets.</p>
205<pre><code class="language-js"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dgram'</span>);
206<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
207
208server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
209  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
210  server.<span class="hljs-title function_">close</span>();
211});
212
213server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
214  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
215});
216
217server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
218  <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
219  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
220});
221
222server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
223<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code></pre>
224<section><h3>Class: <code>dgram.Socket</code><span><a class="mark" href="#dgram_class_dgram_socket" id="dgram_class_dgram_socket">#</a></span></h3>
225<div class="api_metadata">
226<span>Added in: v0.1.99</span>
227</div>
228<ul>
229<li>Extends: <a href="events.html#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
230</ul>
231<p>Encapsulates the datagram functionality.</p>
232<p>New instances of <code>dgram.Socket</code> are created using <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>.
233The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p>
234<h4>Event: <code>'close'</code><span><a class="mark" href="#dgram_event_close" id="dgram_event_close">#</a></span></h4>
235<div class="api_metadata">
236<span>Added in: v0.1.99</span>
237</div>
238<p>The <code>'close'</code> event is emitted after a socket is closed with <a href="#dgram_socket_close_callback"><code>close()</code></a>.
239Once triggered, no new <code>'message'</code> events will be emitted on this socket.</p>
240<h4>Event: <code>'connect'</code><span><a class="mark" href="#dgram_event_connect" id="dgram_event_connect">#</a></span></h4>
241<div class="api_metadata">
242<span>Added in: v12.0.0</span>
243</div>
244<p>The <code>'connect'</code> event is emitted after a socket is associated to a remote
245address as a result of a successful <a href="#dgram_socket_connect_port_address_callback"><code>connect()</code></a> call.</p>
246<h4>Event: <code>'error'</code><span><a class="mark" href="#dgram_event_error" id="dgram_event_error">#</a></span></h4>
247<div class="api_metadata">
248<span>Added in: v0.1.99</span>
249</div>
250<ul>
251<li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
252</ul>
253<p>The <code>'error'</code> event is emitted whenever any error occurs. The event handler
254function is passed a single <code>Error</code> object.</p>
255<h4>Event: <code>'listening'</code><span><a class="mark" href="#dgram_event_listening" id="dgram_event_listening">#</a></span></h4>
256<div class="api_metadata">
257<span>Added in: v0.1.99</span>
258</div>
259<p>The <code>'listening'</code> event is emitted once the <code>dgram.Socket</code> is addressable and
260can receive data. This happens either explicitly with <code>socket.bind()</code> or
261implicitly the first time data is sent using <code>socket.send()</code>.
262Until the <code>dgram.Socket</code> is listening, the underlying system resources do not
263exist and calls such as <code>socket.address()</code> and <code>socket.setTTL()</code> will fail.</p>
264<h4>Event: <code>'message'</code><span><a class="mark" href="#dgram_event_message" id="dgram_event_message">#</a></span></h4>
265<div class="api_metadata">
266<span>Added in: v0.1.99</span>
267</div>
268<p>The <code>'message'</code> event is emitted when a new datagram is available on a socket.
269The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>.</p>
270<ul>
271<li><code>msg</code> <a href="buffer.html#buffer_class_buffer" class="type">&#x3C;Buffer></a> The message.</li>
272<li><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Remote address information.
273<ul>
274<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The sender address.</li>
275<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The address family (<code>'IPv4'</code> or <code>'IPv6'</code>).</li>
276<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The sender port.</li>
277<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The message size.</li>
278</ul>
279</li>
280</ul>
281<p>If the source address of the incoming packet is an IPv6 link-local
282address, the interface name is added to the <code>address</code>. For
283example, a packet received on the <code>en0</code> interface might have the
284address field set to <code>'fe80::2618:1234:ab11:3b9c%en0'</code>, where <code>'%en0'</code>
285is the interface name as a zone ID suffix.</p>
286<h4><code>socket.addMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#dgram_socket_addmembership_multicastaddress_multicastinterface" id="dgram_socket_addmembership_multicastaddress_multicastinterface">#</a></span></h4>
287<div class="api_metadata">
288<span>Added in: v0.6.9</span>
289</div>
290<ul>
291<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
292<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
293</ul>
294<p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and
295<code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the
296<code>multicastInterface</code> argument is not specified, the operating system will choose
297one interface and will add membership to it. To add membership to every
298available interface, call <code>addMembership</code> multiple times, once per interface.</p>
299<p>When called on an unbound socket, this method will implicitly bind to a random
300port, listening on all interfaces.</p>
301<p>When sharing a UDP socket across multiple <code>cluster</code> workers, the
302<code>socket.addMembership()</code> function must be called only once or an
303<code>EADDRINUSE</code> error will occur:</p>
304<pre><code class="language-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>);
305<span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dgram'</span>);
306<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isMaster</span>) {
307  cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span>
308  cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span>
309} <span class="hljs-keyword">else</span> {
310  <span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
311  s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
312    s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>);
313  });
314}</code></pre>
315<h4><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface" id="dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface">#</a></span></h4>
316<div class="api_metadata">
317<span>Added in: v13.1.0, v12.16.0</span>
318</div>
319<ul>
320<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
321<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
322<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
323</ul>
324<p>Tells the kernel to join a source-specific multicast channel at the given
325<code>sourceAddress</code> and <code>groupAddress</code>, using the <code>multicastInterface</code> with the
326<code>IP_ADD_SOURCE_MEMBERSHIP</code> socket option. If the <code>multicastInterface</code> argument
327is not specified, the operating system will choose one interface and will add
328membership to it. To add membership to every available interface, call
329<code>socket.addSourceSpecificMembership()</code> multiple times, once per interface.</p>
330<p>When called on an unbound socket, this method will implicitly bind to a random
331port, listening on all interfaces.</p>
332<h4><code>socket.address()</code><span><a class="mark" href="#dgram_socket_address" id="dgram_socket_address">#</a></span></h4>
333<div class="api_metadata">
334<span>Added in: v0.1.99</span>
335</div>
336<ul>
337<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
338</ul>
339<p>Returns an object containing the address information for a socket.
340For UDP sockets, this object will contain <code>address</code>, <code>family</code> and <code>port</code>
341properties.</p>
342<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
343<h4><code>socket.bind([port][, address][, callback])</code><span><a class="mark" href="#dgram_socket_bind_port_address_callback" id="dgram_socket_bind_port_address_callback">#</a></span></h4>
344<div class="api_metadata">
345<details class="changelog"><summary>History</summary>
346<table>
347<tbody><tr><th>Version</th><th>Changes</th></tr>
348<tr><td>v0.9.1</td>
349<td><p>The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call.</p></td></tr>
350<tr><td>v0.1.99</td>
351<td><p><span>Added in: v0.1.99</span></p></td></tr>
352</tbody></table>
353</details>
354</div>
355<ul>
356<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
357<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
358<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> with no parameters. Called when binding is complete.</li>
359</ul>
360<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram
361messages on a named <code>port</code> and optional <code>address</code>. If <code>port</code> is not
362specified or is <code>0</code>, the operating system will attempt to bind to a
363random port. If <code>address</code> is not specified, the operating system will
364attempt to listen on all addresses. Once binding is complete, a
365<code>'listening'</code> event is emitted and the optional <code>callback</code> function is
366called.</p>
367<p>Specifying both a <code>'listening'</code> event listener and passing a
368<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
369useful.</p>
370<p>A bound datagram socket keeps the Node.js process running to receive
371datagram messages.</p>
372<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g.
373attempting to bind with a closed socket), an <a href="errors.html#errors_class_error"><code>Error</code></a> may be thrown.</p>
374<p>Example of a UDP server listening on port 41234:</p>
375<pre><code class="language-js"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dgram'</span>);
376<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
377
378server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
379  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
380  server.<span class="hljs-title function_">close</span>();
381});
382
383server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
384  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
385});
386
387server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
388  <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
389  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
390});
391
392server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
393<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code></pre>
394<h4><code>socket.bind(options[, callback])</code><span><a class="mark" href="#dgram_socket_bind_options_callback" id="dgram_socket_bind_options_callback">#</a></span></h4>
395<div class="api_metadata">
396<span>Added in: v0.11.14</span>
397</div>
398<ul>
399<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Required. Supports the following properties:
400<ul>
401<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
402<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
403<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
404<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
405</ul>
406</li>
407<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
408</ul>
409<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram
410messages on a named <code>port</code> and optional <code>address</code> that are passed as
411properties of an <code>options</code> object passed as the first argument. If
412<code>port</code> is not specified or is <code>0</code>, the operating system will attempt
413to bind to a random port. If <code>address</code> is not specified, the operating
414system will attempt to listen on all addresses. Once binding is
415complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code>
416function is called.</p>
417<p>The <code>options</code> object may contain a <code>fd</code> property. When a <code>fd</code> greater
418than <code>0</code> is set, it will wrap around an existing socket with the given
419file descriptor. In this case, the properties of <code>port</code> and <code>address</code>
420will be ignored.</p>
421<p>Specifying both a <code>'listening'</code> event listener and passing a
422<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
423useful.</p>
424<p>The <code>options</code> object may contain an additional <code>exclusive</code> property that is
425used when using <code>dgram.Socket</code> objects with the <a href="cluster.html"><code>cluster</code></a> module. When
426<code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same
427underlying socket handle allowing connection handling duties to be shared.
428When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted
429port sharing results in an error.</p>
430<p>A bound datagram socket keeps the Node.js process running to receive
431datagram messages.</p>
432<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g.
433attempting to bind with a closed socket), an <a href="errors.html#errors_class_error"><code>Error</code></a> may be thrown.</p>
434<p>An example socket listening on an exclusive port is shown below.</p>
435<pre><code class="language-js">socket.<span class="hljs-title function_">bind</span>({
436  <span class="hljs-attr">address</span>: <span class="hljs-string">'localhost'</span>,
437  <span class="hljs-attr">port</span>: <span class="hljs-number">8000</span>,
438  <span class="hljs-attr">exclusive</span>: <span class="hljs-literal">true</span>
439});</code></pre>
440<h4><code>socket.close([callback])</code><span><a class="mark" href="#dgram_socket_close_callback" id="dgram_socket_close_callback">#</a></span></h4>
441<div class="api_metadata">
442<span>Added in: v0.1.99</span>
443</div>
444<ul>
445<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the socket has been closed.</li>
446</ul>
447<p>Close the underlying socket and stop listening for data on it. If a callback is
448provided, it is added as a listener for the <a href="#dgram_event_close"><code>'close'</code></a> event.</p>
449<h4><code>socket.connect(port[, address][, callback])</code><span><a class="mark" href="#dgram_socket_connect_port_address_callback" id="dgram_socket_connect_port_address_callback">#</a></span></h4>
450<div class="api_metadata">
451<span>Added in: v12.0.0</span>
452</div>
453<ul>
454<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
455<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
456<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the connection is completed or on error.</li>
457</ul>
458<p>Associates the <code>dgram.Socket</code> to a remote address and port. Every
459message sent by this handle is automatically sent to that destination. Also,
460the socket will only receive messages from that remote peer.
461Trying to call <code>connect()</code> on an already connected socket will result
462in an <a href="errors.html#errors_err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a> exception. If <code>address</code> is not
463provided, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code> (for <code>udp6</code> sockets)
464will be used by default. Once the connection is complete, a <code>'connect'</code> event
465is emitted and the optional <code>callback</code> function is called. In case of failure,
466the <code>callback</code> is called or, failing this, an <code>'error'</code> event is emitted.</p>
467<h4><code>socket.disconnect()</code><span><a class="mark" href="#dgram_socket_disconnect" id="dgram_socket_disconnect">#</a></span></h4>
468<div class="api_metadata">
469<span>Added in: v12.0.0</span>
470</div>
471<p>A synchronous function that disassociates a connected <code>dgram.Socket</code> from
472its remote address. Trying to call <code>disconnect()</code> on an unbound or already
473disconnected socket will result in an <a href="errors.html#errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a>
474exception.</p>
475<h4><code>socket.dropMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#dgram_socket_dropmembership_multicastaddress_multicastinterface" id="dgram_socket_dropmembership_multicastaddress_multicastinterface">#</a></span></h4>
476<div class="api_metadata">
477<span>Added in: v0.6.9</span>
478</div>
479<ul>
480<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
481<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
482</ul>
483<p>Instructs the kernel to leave a multicast group at <code>multicastAddress</code> using the
484<code>IP_DROP_MEMBERSHIP</code> socket option. This method is automatically called by the
485kernel when the socket is closed or the process terminates, so most apps will
486never have reason to call this.</p>
487<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to
488drop membership on all valid interfaces.</p>
489<h4><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface" id="dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface">#</a></span></h4>
490<div class="api_metadata">
491<span>Added in: v13.1.0, v12.16.0</span>
492</div>
493<ul>
494<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
495<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
496<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
497</ul>
498<p>Instructs the kernel to leave a source-specific multicast channel at the given
499<code>sourceAddress</code> and <code>groupAddress</code> using the <code>IP_DROP_SOURCE_MEMBERSHIP</code>
500socket option. This method is automatically called by the kernel when the
501socket is closed or the process terminates, so most apps will never have
502reason to call this.</p>
503<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to
504drop membership on all valid interfaces.</p>
505<h4><code>socket.getRecvBufferSize()</code><span><a class="mark" href="#dgram_socket_getrecvbuffersize" id="dgram_socket_getrecvbuffersize">#</a></span></h4>
506<div class="api_metadata">
507<span>Added in: v8.7.0</span>
508</div>
509<ul>
510<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the <code>SO_RCVBUF</code> socket receive buffer size in bytes.</li>
511</ul>
512<p>This method throws <a href="errors.html#errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
513<h4><code>socket.getSendBufferSize()</code><span><a class="mark" href="#dgram_socket_getsendbuffersize" id="dgram_socket_getsendbuffersize">#</a></span></h4>
514<div class="api_metadata">
515<span>Added in: v8.7.0</span>
516</div>
517<ul>
518<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the <code>SO_SNDBUF</code> socket send buffer size in bytes.</li>
519</ul>
520<p>This method throws <a href="errors.html#errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
521<h4><code>socket.ref()</code><span><a class="mark" href="#dgram_socket_ref" id="dgram_socket_ref">#</a></span></h4>
522<div class="api_metadata">
523<span>Added in: v0.9.1</span>
524</div>
525<ul>
526<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
527</ul>
528<p>By default, binding a socket will cause it to block the Node.js process from
529exiting as long as the socket is open. The <code>socket.unref()</code> method can be used
530to exclude the socket from the reference counting that keeps the Node.js
531process active. The <code>socket.ref()</code> method adds the socket back to the reference
532counting and restores the default behavior.</p>
533<p>Calling <code>socket.ref()</code> multiples times will have no additional effect.</p>
534<p>The <code>socket.ref()</code> method returns a reference to the socket so calls can be
535chained.</p>
536<h4><code>socket.remoteAddress()</code><span><a class="mark" href="#dgram_socket_remoteaddress" id="dgram_socket_remoteaddress">#</a></span></h4>
537<div class="api_metadata">
538<span>Added in: v12.0.0</span>
539</div>
540<ul>
541<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
542</ul>
543<p>Returns an object containing the <code>address</code>, <code>family</code>, and <code>port</code> of the remote
544endpoint. This method throws an <a href="errors.html#errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> exception
545if the socket is not connected.</p>
546<h4><code>socket.send(msg[, offset, length][, port][, address][, callback])</code><span><a class="mark" href="#dgram_socket_send_msg_offset_length_port_address_callback" id="dgram_socket_send_msg_offset_length_port_address_callback">#</a></span></h4>
547<div class="api_metadata">
548<details class="changelog"><summary>History</summary>
549<table>
550<tbody><tr><th>Version</th><th>Changes</th></tr>
551<tr><td>v14.5.0</td>
552<td><p>The <code>msg</code> parameter can now be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
553<tr><td>v12.0.0</td>
554<td><p>Added support for sending data on connected sockets.</p></td></tr>
555<tr><td>v8.0.0</td>
556<td><p>The <code>msg</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
557<tr><td>v8.0.0</td>
558<td><p>The <code>address</code> parameter is always optional now.</p></td></tr>
559<tr><td>v6.0.0</td>
560<td><p>On success, <code>callback</code> will now be called with an <code>error</code> argument of <code>null</code> rather than <code>0</code>.</p></td></tr>
561<tr><td>v5.7.0</td>
562<td><p>The <code>msg</code> parameter can be an array now. Also, the <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
563<tr><td>v0.1.99</td>
564<td><p><span>Added in: v0.1.99</span></p></td></tr>
565</tbody></table>
566</details>
567</div>
568<ul>
569<li><code>msg</code> <a href="buffer.html#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> Message to be sent.</li>
570<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Offset in the buffer where the message starts.</li>
571<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes in the message.</li>
572<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Destination port.</li>
573<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Destination host name or IP address.</li>
574<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the message has been sent.</li>
575</ul>
576<p>Broadcasts a datagram on the socket.
577For connectionless sockets, the destination <code>port</code> and <code>address</code> must be
578specified. Connected sockets, on the other hand, will use their associated
579remote endpoint, so the <code>port</code> and <code>address</code> arguments must not be set.</p>
580<p>The <code>msg</code> argument contains the message to be sent.
581Depending on its type, different behavior can apply. If <code>msg</code> is a <code>Buffer</code>,
582any <code>TypedArray</code> or a <code>DataView</code>,
583the <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the
584message begins and the number of bytes in the message, respectively.
585If <code>msg</code> is a <code>String</code>, then it is automatically converted to a <code>Buffer</code>
586with <code>'utf8'</code> encoding. With messages that
587contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with
588respect to <a href="buffer.html#buffer_static_method_buffer_bytelength_string_encoding">byte length</a> and not the character position.
589If <code>msg</code> is an array, <code>offset</code> and <code>length</code> must not be specified.</p>
590<p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name,
591DNS will be used to resolve the address of the host. If <code>address</code> is not
592provided or otherwise falsy, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code>
593(for <code>udp6</code> sockets) will be used by default.</p>
594<p>If the socket has not been previously bound with a call to <code>bind</code>, the socket
595is assigned a random port number and is bound to the "all interfaces" address
596(<code>'0.0.0.0'</code> for <code>udp4</code> sockets, <code>'::0'</code> for <code>udp6</code> sockets.)</p>
597<p>An optional <code>callback</code> function may be specified to as a way of reporting
598DNS errors or for determining when it is safe to reuse the <code>buf</code> object.
599DNS lookups delay the time to send for at least one tick of the
600Node.js event loop.</p>
601<p>The only way to know for sure that the datagram has been sent is by using a
602<code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be
603passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given,
604the error is emitted as an <code>'error'</code> event on the <code>socket</code> object.</p>
605<p>Offset and length are optional but both <em>must</em> be set if either are used.
606They are supported only when the first argument is a <code>Buffer</code>, a <code>TypedArray</code>,
607or a <code>DataView</code>.</p>
608<p>This method throws <a href="errors.html#errors_err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a> if called on an unbound socket.</p>
609<p>Example of sending a UDP packet to a port on <code>localhost</code>;</p>
610<pre><code class="language-js"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dgram'</span>);
611<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
612<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
613client.<span class="hljs-title function_">send</span>(message, <span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
614  client.<span class="hljs-title function_">close</span>();
615});</code></pre>
616<p>Example of sending a UDP packet composed of multiple buffers to a port on
617<code>127.0.0.1</code>;</p>
618<pre><code class="language-js"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dgram'</span>);
619<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some '</span>);
620<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'bytes'</span>);
621<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
622client.<span class="hljs-title function_">send</span>([buf1, buf2], <span class="hljs-number">41234</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
623  client.<span class="hljs-title function_">close</span>();
624});</code></pre>
625<p>Sending multiple buffers might be faster or slower depending on the
626application and operating system. Run benchmarks to
627determine the optimal strategy on a case-by-case basis. Generally speaking,
628however, sending multiple buffers is faster.</p>
629<p>Example of sending a UDP packet using a socket connected to a port on
630<code>localhost</code>:</p>
631<pre><code class="language-js"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dgram'</span>);
632<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
633<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
634client.<span class="hljs-title function_">connect</span>(<span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
635  client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
636    client.<span class="hljs-title function_">close</span>();
637  });
638});</code></pre>
639<h5>Note about UDP datagram size<span><a class="mark" href="#dgram_note_about_udp_datagram_size" id="dgram_note_about_udp_datagram_size">#</a></span></h5>
640<p>The maximum size of an IPv4/v6 datagram depends on the <code>MTU</code>
641(Maximum Transmission Unit) and on the <code>Payload Length</code> field size.</p>
642<ul>
643<li>
644<p>The <code>Payload Length</code> field is 16 bits wide, which means that a normal
645payload cannot exceed 64K octets including the internet header and data
646(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
647this is generally true for loopback interfaces, but such long datagram
648messages are impractical for most hosts and networks.</p>
649</li>
650<li>
651<p>The <code>MTU</code> is the largest size a given link layer technology can support for
652datagram messages. For any link, IPv4 mandates a minimum <code>MTU</code> of 68
653octets, while the recommended <code>MTU</code> for IPv4 is 576 (typically recommended
654as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in
655fragments.</p>
656<p>For IPv6, the minimum <code>MTU</code> is 1280 octets. However, the mandatory minimum
657fragment reassembly buffer size is 1500 octets. The value of 68 octets is
658very small, since most current link layer technologies, like Ethernet, have a
659minimum <code>MTU</code> of 1500.</p>
660</li>
661</ul>
662<p>It is impossible to know in advance the MTU of each link through which
663a packet might travel. Sending a datagram greater than the receiver <code>MTU</code> will
664not work because the packet will get silently dropped without informing the
665source that the data did not reach its intended recipient.</p>
666<h4><code>socket.setBroadcast(flag)</code><span><a class="mark" href="#dgram_socket_setbroadcast_flag" id="dgram_socket_setbroadcast_flag">#</a></span></h4>
667<div class="api_metadata">
668<span>Added in: v0.6.9</span>
669</div>
670<ul>
671<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
672</ul>
673<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When set to <code>true</code>, UDP
674packets may be sent to a local interface's broadcast address.</p>
675<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
676<h4><code>socket.setMulticastInterface(multicastInterface)</code><span><a class="mark" href="#dgram_socket_setmulticastinterface_multicastinterface" id="dgram_socket_setmulticastinterface_multicastinterface">#</a></span></h4>
677<div class="api_metadata">
678<span>Added in: v8.6.0</span>
679</div>
680<ul>
681<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
682</ul>
683<p><em>All references to scope in this section are referring to
684<a href="https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses">IPv6 Zone Indices</a>, which are defined by <a href="https://tools.ietf.org/html/rfc4007">RFC 4007</a>. In string form, an IP
685with a scope index is written as <code>'IP%scope'</code> where scope is an interface name
686or interface number.</em></p>
687<p>Sets the default outgoing multicast interface of the socket to a chosen
688interface or back to system interface selection. The <code>multicastInterface</code> must
689be a valid string representation of an IP from the socket's family.</p>
690<p>For IPv4 sockets, this should be the IP configured for the desired physical
691interface. All packets sent to multicast on the socket will be sent on the
692interface determined by the most recent successful use of this call.</p>
693<p>For IPv6 sockets, <code>multicastInterface</code> should include a scope to indicate the
694interface as in the examples that follow. In IPv6, individual <code>send</code> calls can
695also use explicit scope in addresses, so only packets sent to a multicast
696address without specifying an explicit scope are affected by the most recent
697successful use of this call.</p>
698<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
699<h5>Example: IPv6 outgoing multicast interface<span><a class="mark" href="#dgram_example_ipv6_outgoing_multicast_interface" id="dgram_example_ipv6_outgoing_multicast_interface">#</a></span></h5>
700<p>On most systems, where scope format uses the interface name:</p>
701<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp6'</span>);
702
703socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
704  socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%eth1'</span>);
705});</code></pre>
706<p>On Windows, where scope format uses an interface number:</p>
707<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp6'</span>);
708
709socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
710  socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%2'</span>);
711});</code></pre>
712<h5>Example: IPv4 outgoing multicast interface<span><a class="mark" href="#dgram_example_ipv4_outgoing_multicast_interface" id="dgram_example_ipv4_outgoing_multicast_interface">#</a></span></h5>
713<p>All systems use an IP of the host on the desired physical interface:</p>
714<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
715
716socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
717  socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'10.0.0.2'</span>);
718});</code></pre>
719<h5>Call results<span><a class="mark" href="#dgram_call_results" id="dgram_call_results">#</a></span></h5>
720<p>A call on a socket that is not ready to send or no longer open may throw a <em>Not
721running</em> <a href="errors.html#errors_class_error"><code>Error</code></a>.</p>
722<p>If <code>multicastInterface</code> can not be parsed into an IP then an <em>EINVAL</em>
723<a href="errors.html#errors_class_systemerror"><code>System Error</code></a> is thrown.</p>
724<p>On IPv4, if <code>multicastInterface</code> is a valid address but does not match any
725interface, or if the address does not match the family then
726a <a href="errors.html#errors_class_systemerror"><code>System Error</code></a> such as <code>EADDRNOTAVAIL</code> or <code>EPROTONOSUP</code> is thrown.</p>
727<p>On IPv6, most errors with specifying or omitting scope will result in the socket
728continuing to use (or returning to) the system's default interface selection.</p>
729<p>A socket's address family's ANY address (IPv4 <code>'0.0.0.0'</code> or IPv6 <code>'::'</code>) can be
730used to return control of the sockets default outgoing interface to the system
731for future multicast packets.</p>
732<h4><code>socket.setMulticastLoopback(flag)</code><span><a class="mark" href="#dgram_socket_setmulticastloopback_flag" id="dgram_socket_setmulticastloopback_flag">#</a></span></h4>
733<div class="api_metadata">
734<span>Added in: v0.3.8</span>
735</div>
736<ul>
737<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
738</ul>
739<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When set to <code>true</code>,
740multicast packets will also be received on the local interface.</p>
741<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
742<h4><code>socket.setMulticastTTL(ttl)</code><span><a class="mark" href="#dgram_socket_setmulticastttl_ttl" id="dgram_socket_setmulticastttl_ttl">#</a></span></h4>
743<div class="api_metadata">
744<span>Added in: v0.3.8</span>
745</div>
746<ul>
747<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
748</ul>
749<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. While TTL generally stands for
750"Time to Live", in this context it specifies the number of IP hops that a
751packet is allowed to travel through, specifically for multicast traffic. Each
752router or gateway that forwards a packet decrements the TTL. If the TTL is
753decremented to 0 by a router, it will not be forwarded.</p>
754<p>The <code>ttl</code> argument may be between 0 and 255. The default on most systems is <code>1</code>.</p>
755<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
756<h4><code>socket.setRecvBufferSize(size)</code><span><a class="mark" href="#dgram_socket_setrecvbuffersize_size" id="dgram_socket_setrecvbuffersize_size">#</a></span></h4>
757<div class="api_metadata">
758<span>Added in: v8.7.0</span>
759</div>
760<ul>
761<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
762</ul>
763<p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer
764in bytes.</p>
765<p>This method throws <a href="errors.html#errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
766<h4><code>socket.setSendBufferSize(size)</code><span><a class="mark" href="#dgram_socket_setsendbuffersize_size" id="dgram_socket_setsendbuffersize_size">#</a></span></h4>
767<div class="api_metadata">
768<span>Added in: v8.7.0</span>
769</div>
770<ul>
771<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
772</ul>
773<p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer
774in bytes.</p>
775<p>This method throws <a href="errors.html#errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
776<h4><code>socket.setTTL(ttl)</code><span><a class="mark" href="#dgram_socket_setttl_ttl" id="dgram_socket_setttl_ttl">#</a></span></h4>
777<div class="api_metadata">
778<span>Added in: v0.1.101</span>
779</div>
780<ul>
781<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
782</ul>
783<p>Sets the <code>IP_TTL</code> socket option. While TTL generally stands for "Time to Live",
784in this context it specifies the number of IP hops that a packet is allowed to
785travel through. Each router or gateway that forwards a packet decrements the
786TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
787Changing TTL values is typically done for network probes or when multicasting.</p>
788<p>The <code>ttl</code> argument may be between between 1 and 255. The default on most systems
789is 64.</p>
790<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
791<h4><code>socket.unref()</code><span><a class="mark" href="#dgram_socket_unref" id="dgram_socket_unref">#</a></span></h4>
792<div class="api_metadata">
793<span>Added in: v0.9.1</span>
794</div>
795<ul>
796<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
797</ul>
798<p>By default, binding a socket will cause it to block the Node.js process from
799exiting as long as the socket is open. The <code>socket.unref()</code> method can be used
800to exclude the socket from the reference counting that keeps the Node.js
801process active, allowing the process to exit even if the socket is still
802listening.</p>
803<p>Calling <code>socket.unref()</code> multiple times will have no addition effect.</p>
804<p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be
805chained.</p>
806</section><section><h3><code>dgram</code> module functions<span><a class="mark" href="#dgram_dgram_module_functions" id="dgram_dgram_module_functions">#</a></span></h3>
807<h4><code>dgram.createSocket(options[, callback])</code><span><a class="mark" href="#dgram_dgram_createsocket_options_callback" id="dgram_dgram_createsocket_options_callback">#</a></span></h4>
808<div class="api_metadata">
809<details class="changelog"><summary>History</summary>
810<table>
811<tbody><tr><th>Version</th><th>Changes</th></tr>
812<tr><td>v14.17.0</td>
813<td><p>AbortSignal support was added.</p></td></tr>
814<tr><td>v11.4.0</td>
815<td><p>The <code>ipv6Only</code> option is supported.</p></td></tr>
816<tr><td>v8.7.0</td>
817<td><p>The <code>recvBufferSize</code> and <code>sendBufferSize</code> options are supported now.</p></td></tr>
818<tr><td>v8.6.0</td>
819<td><p>The <code>lookup</code> option is supported.</p></td></tr>
820<tr><td>v0.11.13</td>
821<td><p><span>Added in: v0.11.13</span></p></td></tr>
822</tbody></table>
823</details>
824</div>
825<ul>
826<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Available options are:
827<ul>
828<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The family of socket. Must be either <code>'udp4'</code> or <code>'udp6'</code>.
829Required.</li>
830<li><code>reuseAddr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code> <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will reuse the
831address, even if another process has already bound a socket on it.
832<strong>Default:</strong> <code>false</code>.</li>
833<li><code>ipv6Only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Setting <code>ipv6Only</code> to <code>true</code> will
834disable dual-stack support, i.e., binding to address <code>::</code> won't make
835<code>0.0.0.0</code> be bound. <strong>Default:</strong> <code>false</code>.</li>
836<li><code>recvBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the <code>SO_RCVBUF</code> socket value.</li>
837<li><code>sendBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the <code>SO_SNDBUF</code> socket value.</li>
838<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Custom lookup function. <strong>Default:</strong> <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
839<li><code>signal</code> <a href="globals.html#globals_class_abortsignal" class="type">&#x3C;AbortSignal></a> An AbortSignal that may be used to close a socket.</li>
840</ul>
841</li>
842<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Attached as a listener for <code>'message'</code> events. Optional.</li>
843<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
844</ul>
845<p>Creates a <code>dgram.Socket</code> object. Once the socket is created, calling
846<a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram
847messages. When <code>address</code> and <code>port</code> are not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the
848method will bind the socket to the "all interfaces" address on a random port
849(it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address
850and port can be retrieved using <a href="#dgram_socket_address"><code>socket.address().address</code></a> and
851<a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p>
852<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
853<code>AbortController</code> is similar to calling <code>.close()</code> on the socket:</p>
854<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
855<span class="hljs-keyword">const</span> { signal } = controller;
856<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'udp4'</span>, signal });
857server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
858  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
859});
860<span class="hljs-comment">// Later, when you want to close the server.</span>
861controller.<span class="hljs-title function_">abort</span>();</code></pre>
862<h4><code>dgram.createSocket(type[, callback])</code><span><a class="mark" href="#dgram_dgram_createsocket_type_callback" id="dgram_dgram_createsocket_type_callback">#</a></span></h4>
863<div class="api_metadata">
864<span>Added in: v0.1.99</span>
865</div>
866<ul>
867<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Either <code>'udp4'</code> or <code>'udp6'</code>.</li>
868<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Attached as a listener to <code>'message'</code> events.</li>
869<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
870</ul>
871<p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>.</p>
872<p>Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the
873socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are
874not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the "all
875interfaces" address on a random port (it does the right thing for both <code>udp4</code>
876and <code>udp6</code> sockets). The bound address and port can be retrieved using
877<a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p></section>
878        <!-- API END -->
879      </div>
880    </div>
881  </div>
882  <script>
883    'use strict';
884    {
885      const kCustomPreference = 'customDarkTheme';
886      const userSettings = sessionStorage.getItem(kCustomPreference);
887      const themeToggleButton = document.getElementById('theme-toggle-btn');
888      if (userSettings === null && window.matchMedia) {
889        const mq = window.matchMedia('(prefers-color-scheme: dark)');
890        if ('onchange' in mq) {
891          function mqChangeListener(e) {
892            document.body.classList.toggle('dark-mode', e.matches);
893          }
894          mq.addEventListener('change', mqChangeListener);
895          if (themeToggleButton) {
896            themeToggleButton.addEventListener('click', function() {
897              mq.removeEventListener('change', mqChangeListener);
898            }, { once: true });
899          }
900        }
901        if (mq.matches) {
902          document.body.classList.add('dark-mode');
903        }
904      } else if (userSettings === 'true') {
905        document.body.classList.add('dark-mode');
906      }
907      if (themeToggleButton) {
908        themeToggleButton.hidden = false;
909        themeToggleButton.addEventListener('click', function() {
910          sessionStorage.setItem(
911            kCustomPreference,
912            document.body.classList.toggle('dark-mode')
913          );
914        });
915      }
916    }
917  </script>
918</body>
919</html>
920