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="v18.20.1"> 7 <title>UDP/datagram sockets | Node.js v18.20.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 <script async defer src="assets/api.js" type="text/javascript"></script> 13 <style>@media(max-width:558px){.with-42-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:542px){.with-40-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style> 14</head> 15<body class="alt apidoc" id="api-section-dgram"> 16 <div id="content" class="clearfix"> 17 <div id="column2" class="interior"> 18 <div id="intro" class="interior"> 19 <a href="/" title="Go back to the home page"> 20 Node.js 21 </a> 22 </div> 23 <ul> 24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 26</ul> 27<hr class="line"> 28<ul> 29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> 31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 33<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 38<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 39<li><a href="console.html" class="nav-console">Console</a></li> 40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 45<li><a href="dns.html" class="nav-dns">DNS</a></li> 46<li><a href="domain.html" class="nav-domain">Domain</a></li> 47<li><a href="errors.html" class="nav-errors">Errors</a></li> 48<li><a href="events.html" class="nav-events">Events</a></li> 49<li><a href="fs.html" class="nav-fs">File system</a></li> 50<li><a href="globals.html" class="nav-globals">Globals</a></li> 51<li><a href="http.html" class="nav-http">HTTP</a></li> 52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 53<li><a href="https.html" class="nav-https">HTTPS</a></li> 54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 55<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> 59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 60<li><a href="net.html" class="nav-net">Net</a></li> 61<li><a href="os.html" class="nav-os">OS</a></li> 62<li><a href="path.html" class="nav-path">Path</a></li> 63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li> 65<li><a href="process.html" class="nav-process">Process</a></li> 66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 68<li><a href="readline.html" class="nav-readline">Readline</a></li> 69<li><a href="repl.html" class="nav-repl">REPL</a></li> 70<li><a href="report.html" class="nav-report">Report</a></li> 71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> 72<li><a href="stream.html" class="nav-stream">Stream</a></li> 73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 74<li><a href="test.html" class="nav-test">Test runner</a></li> 75<li><a href="timers.html" class="nav-timers">Timers</a></li> 76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 78<li><a href="tty.html" class="nav-tty">TTY</a></li> 79<li><a href="dgram.html" class="nav-dgram active">UDP/datagram</a></li> 80<li><a href="url.html" class="nav-url">URL</a></li> 81<li><a href="util.html" class="nav-util">Utilities</a></li> 82<li><a href="v8.html" class="nav-v8">V8</a></li> 83<li><a href="vm.html" class="nav-vm">VM</a></li> 84<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> 86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> 87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 89</ul> 90<hr class="line"> 91<ul> 92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 93</ul> 94 </div> 95 96 <div id="column1" data-id="dgram" class="interior"> 97 <header class="header"> 98 <div class="header-container"> 99 <h1>Node.js v18.20.1 documentation</h1> 100 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 101 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 102 <path fill="none" d="M0 0h24v24H0z" /> 103 <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"/> 104 <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"/> 105 </svg> 106 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 107 <path d="M0 0h24v24H0z" fill="none" /> 108 <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"/> 109 </svg> 110 </button> 111 </div> 112 <div id="gtoc"> 113 <ul> 114 <li class="pinned-header">Node.js v18.20.1</li> 115 116 <li class="picker-header"> 117 <a href="#"> 118 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 119 Table of contents 120 </a> 121 122 <div class="picker"><div class="toc"><ul> 123<li><span class="stability_2"><a href="#udpdatagram-sockets">UDP/datagram sockets</a></span> 124<ul> 125<li><a href="#class-dgramsocket">Class: <code>dgram.Socket</code></a> 126<ul> 127<li><a href="#event-close">Event: <code>'close'</code></a></li> 128<li><a href="#event-connect">Event: <code>'connect'</code></a></li> 129<li><a href="#event-error">Event: <code>'error'</code></a></li> 130<li><a href="#event-listening">Event: <code>'listening'</code></a></li> 131<li><a href="#event-message">Event: <code>'message'</code></a></li> 132<li><a href="#socketaddmembershipmulticastaddress-multicastinterface"><code>socket.addMembership(multicastAddress[, multicastInterface])</code></a></li> 133<li><a href="#socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li> 134<li><a href="#socketaddress"><code>socket.address()</code></a></li> 135<li><a href="#socketbindport-address-callback"><code>socket.bind([port][, address][, callback])</code></a></li> 136<li><a href="#socketbindoptions-callback"><code>socket.bind(options[, callback])</code></a></li> 137<li><a href="#socketclosecallback"><code>socket.close([callback])</code></a></li> 138<li><span class="stability_1"><a href="#socketsymbolasyncdispose"><code>socket[Symbol.asyncDispose]()</code></a></span></li> 139<li><a href="#socketconnectport-address-callback"><code>socket.connect(port[, address][, callback])</code></a></li> 140<li><a href="#socketdisconnect"><code>socket.disconnect()</code></a></li> 141<li><a href="#socketdropmembershipmulticastaddress-multicastinterface"><code>socket.dropMembership(multicastAddress[, multicastInterface])</code></a></li> 142<li><a href="#socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li> 143<li><a href="#socketgetrecvbuffersize"><code>socket.getRecvBufferSize()</code></a></li> 144<li><a href="#socketgetsendbuffersize"><code>socket.getSendBufferSize()</code></a></li> 145<li><a href="#socketgetsendqueuesize"><code>socket.getSendQueueSize()</code></a></li> 146<li><a href="#socketgetsendqueuecount"><code>socket.getSendQueueCount()</code></a></li> 147<li><a href="#socketref"><code>socket.ref()</code></a></li> 148<li><a href="#socketremoteaddress"><code>socket.remoteAddress()</code></a></li> 149<li><a href="#socketsendmsg-offset-length-port-address-callback"><code>socket.send(msg[, offset, length][, port][, address][, callback])</code></a> 150<ul> 151<li><a href="#note-about-udp-datagram-size">Note about UDP datagram size</a></li> 152</ul> 153</li> 154<li><a href="#socketsetbroadcastflag"><code>socket.setBroadcast(flag)</code></a></li> 155<li><a href="#socketsetmulticastinterfacemulticastinterface"><code>socket.setMulticastInterface(multicastInterface)</code></a> 156<ul> 157<li><a href="#example-ipv6-outgoing-multicast-interface">Example: IPv6 outgoing multicast interface</a></li> 158<li><a href="#example-ipv4-outgoing-multicast-interface">Example: IPv4 outgoing multicast interface</a></li> 159<li><a href="#call-results">Call results</a></li> 160</ul> 161</li> 162<li><a href="#socketsetmulticastloopbackflag"><code>socket.setMulticastLoopback(flag)</code></a></li> 163<li><a href="#socketsetmulticastttlttl"><code>socket.setMulticastTTL(ttl)</code></a></li> 164<li><a href="#socketsetrecvbuffersizesize"><code>socket.setRecvBufferSize(size)</code></a></li> 165<li><a href="#socketsetsendbuffersizesize"><code>socket.setSendBufferSize(size)</code></a></li> 166<li><a href="#socketsetttlttl"><code>socket.setTTL(ttl)</code></a></li> 167<li><a href="#socketunref"><code>socket.unref()</code></a></li> 168</ul> 169</li> 170<li><a href="#nodedgram-module-functions"><code>node:dgram</code> module functions</a> 171<ul> 172<li><a href="#dgramcreatesocketoptions-callback"><code>dgram.createSocket(options[, callback])</code></a></li> 173<li><a href="#dgramcreatesockettype-callback"><code>dgram.createSocket(type[, callback])</code></a></li> 174</ul> 175</li> 176</ul> 177</li> 178</ul></div></div> 179 </li> 180 181 182 <li class="picker-header"> 183 <a href="#"> 184 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 185 Index 186 </a> 187 188 <div class="picker"><ul> 189<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 190<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 191 192 <li> 193 <a href="index.html">Index</a> 194 </li> 195 </ul> 196 197<hr class="line"> 198<ul> 199<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 200<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> 201<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 202<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 203<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 204<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 205<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 206<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 207<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 208<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 209<li><a href="console.html" class="nav-console">Console</a></li> 210<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 211<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 212<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 213<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 214<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 215<li><a href="dns.html" class="nav-dns">DNS</a></li> 216<li><a href="domain.html" class="nav-domain">Domain</a></li> 217<li><a href="errors.html" class="nav-errors">Errors</a></li> 218<li><a href="events.html" class="nav-events">Events</a></li> 219<li><a href="fs.html" class="nav-fs">File system</a></li> 220<li><a href="globals.html" class="nav-globals">Globals</a></li> 221<li><a href="http.html" class="nav-http">HTTP</a></li> 222<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 223<li><a href="https.html" class="nav-https">HTTPS</a></li> 224<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 225<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 226<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 227<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 228<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> 229<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 230<li><a href="net.html" class="nav-net">Net</a></li> 231<li><a href="os.html" class="nav-os">OS</a></li> 232<li><a href="path.html" class="nav-path">Path</a></li> 233<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 234<li><a href="permissions.html" class="nav-permissions">Permissions</a></li> 235<li><a href="process.html" class="nav-process">Process</a></li> 236<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 237<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 238<li><a href="readline.html" class="nav-readline">Readline</a></li> 239<li><a href="repl.html" class="nav-repl">REPL</a></li> 240<li><a href="report.html" class="nav-report">Report</a></li> 241<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> 242<li><a href="stream.html" class="nav-stream">Stream</a></li> 243<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 244<li><a href="test.html" class="nav-test">Test runner</a></li> 245<li><a href="timers.html" class="nav-timers">Timers</a></li> 246<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 247<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 248<li><a href="tty.html" class="nav-tty">TTY</a></li> 249<li><a href="dgram.html" class="nav-dgram active">UDP/datagram</a></li> 250<li><a href="url.html" class="nav-url">URL</a></li> 251<li><a href="util.html" class="nav-util">Utilities</a></li> 252<li><a href="v8.html" class="nav-v8">V8</a></li> 253<li><a href="vm.html" class="nav-vm">VM</a></li> 254<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 255<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> 256<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> 257<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 258<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 259</ul> 260<hr class="line"> 261<ul> 262<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 263</ul></div> 264 </li> 265 266 267 <li class="picker-header"> 268 <a href="#"> 269 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 270 Other versions 271 </a> 272 <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/dgram.html">21.x</a></li> 273<li><a href="https://nodejs.org/docs/latest-v20.x/api/dgram.html">20.x <b>LTS</b></a></li> 274<li><a href="https://nodejs.org/docs/latest-v19.x/api/dgram.html">19.x</a></li> 275<li><a href="https://nodejs.org/docs/latest-v18.x/api/dgram.html">18.x <b>LTS</b></a></li> 276<li><a href="https://nodejs.org/docs/latest-v17.x/api/dgram.html">17.x</a></li> 277<li><a href="https://nodejs.org/docs/latest-v16.x/api/dgram.html">16.x</a></li> 278<li><a href="https://nodejs.org/docs/latest-v15.x/api/dgram.html">15.x</a></li> 279<li><a href="https://nodejs.org/docs/latest-v14.x/api/dgram.html">14.x</a></li> 280<li><a href="https://nodejs.org/docs/latest-v13.x/api/dgram.html">13.x</a></li> 281<li><a href="https://nodejs.org/docs/latest-v12.x/api/dgram.html">12.x</a></li> 282<li><a href="https://nodejs.org/docs/latest-v11.x/api/dgram.html">11.x</a></li> 283<li><a href="https://nodejs.org/docs/latest-v10.x/api/dgram.html">10.x</a></li> 284<li><a href="https://nodejs.org/docs/latest-v9.x/api/dgram.html">9.x</a></li> 285<li><a href="https://nodejs.org/docs/latest-v8.x/api/dgram.html">8.x</a></li> 286<li><a href="https://nodejs.org/docs/latest-v7.x/api/dgram.html">7.x</a></li> 287<li><a href="https://nodejs.org/docs/latest-v6.x/api/dgram.html">6.x</a></li> 288<li><a href="https://nodejs.org/docs/latest-v5.x/api/dgram.html">5.x</a></li> 289<li><a href="https://nodejs.org/docs/latest-v4.x/api/dgram.html">4.x</a></li> 290<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/dgram.html">0.12.x</a></li> 291<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/dgram.html">0.10.x</a></li></ol></div> 292 </li> 293 294 <li class="picker-header"> 295 <a href="#"> 296 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 297 Options 298 </a> 299 300 <div class="picker"> 301 <ul> 302 <li> 303 <a href="all.html">View on single page</a> 304 </li> 305 <li> 306 <a href="dgram.json">View as JSON</a> 307 </li> 308 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/dgram.md">Edit on GitHub</a></li> 309 </ul> 310 </div> 311 </li> 312 </ul> 313 </div> 314 <hr> 315 </header> 316 317 <details id="toc" open><summary>Table of contents</summary><ul> 318<li><span class="stability_2"><a href="#udpdatagram-sockets">UDP/datagram sockets</a></span> 319<ul> 320<li><a href="#class-dgramsocket">Class: <code>dgram.Socket</code></a> 321<ul> 322<li><a href="#event-close">Event: <code>'close'</code></a></li> 323<li><a href="#event-connect">Event: <code>'connect'</code></a></li> 324<li><a href="#event-error">Event: <code>'error'</code></a></li> 325<li><a href="#event-listening">Event: <code>'listening'</code></a></li> 326<li><a href="#event-message">Event: <code>'message'</code></a></li> 327<li><a href="#socketaddmembershipmulticastaddress-multicastinterface"><code>socket.addMembership(multicastAddress[, multicastInterface])</code></a></li> 328<li><a href="#socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li> 329<li><a href="#socketaddress"><code>socket.address()</code></a></li> 330<li><a href="#socketbindport-address-callback"><code>socket.bind([port][, address][, callback])</code></a></li> 331<li><a href="#socketbindoptions-callback"><code>socket.bind(options[, callback])</code></a></li> 332<li><a href="#socketclosecallback"><code>socket.close([callback])</code></a></li> 333<li><span class="stability_1"><a href="#socketsymbolasyncdispose"><code>socket[Symbol.asyncDispose]()</code></a></span></li> 334<li><a href="#socketconnectport-address-callback"><code>socket.connect(port[, address][, callback])</code></a></li> 335<li><a href="#socketdisconnect"><code>socket.disconnect()</code></a></li> 336<li><a href="#socketdropmembershipmulticastaddress-multicastinterface"><code>socket.dropMembership(multicastAddress[, multicastInterface])</code></a></li> 337<li><a href="#socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li> 338<li><a href="#socketgetrecvbuffersize"><code>socket.getRecvBufferSize()</code></a></li> 339<li><a href="#socketgetsendbuffersize"><code>socket.getSendBufferSize()</code></a></li> 340<li><a href="#socketgetsendqueuesize"><code>socket.getSendQueueSize()</code></a></li> 341<li><a href="#socketgetsendqueuecount"><code>socket.getSendQueueCount()</code></a></li> 342<li><a href="#socketref"><code>socket.ref()</code></a></li> 343<li><a href="#socketremoteaddress"><code>socket.remoteAddress()</code></a></li> 344<li><a href="#socketsendmsg-offset-length-port-address-callback"><code>socket.send(msg[, offset, length][, port][, address][, callback])</code></a> 345<ul> 346<li><a href="#note-about-udp-datagram-size">Note about UDP datagram size</a></li> 347</ul> 348</li> 349<li><a href="#socketsetbroadcastflag"><code>socket.setBroadcast(flag)</code></a></li> 350<li><a href="#socketsetmulticastinterfacemulticastinterface"><code>socket.setMulticastInterface(multicastInterface)</code></a> 351<ul> 352<li><a href="#example-ipv6-outgoing-multicast-interface">Example: IPv6 outgoing multicast interface</a></li> 353<li><a href="#example-ipv4-outgoing-multicast-interface">Example: IPv4 outgoing multicast interface</a></li> 354<li><a href="#call-results">Call results</a></li> 355</ul> 356</li> 357<li><a href="#socketsetmulticastloopbackflag"><code>socket.setMulticastLoopback(flag)</code></a></li> 358<li><a href="#socketsetmulticastttlttl"><code>socket.setMulticastTTL(ttl)</code></a></li> 359<li><a href="#socketsetrecvbuffersizesize"><code>socket.setRecvBufferSize(size)</code></a></li> 360<li><a href="#socketsetsendbuffersizesize"><code>socket.setSendBufferSize(size)</code></a></li> 361<li><a href="#socketsetttlttl"><code>socket.setTTL(ttl)</code></a></li> 362<li><a href="#socketunref"><code>socket.unref()</code></a></li> 363</ul> 364</li> 365<li><a href="#nodedgram-module-functions"><code>node:dgram</code> module functions</a> 366<ul> 367<li><a href="#dgramcreatesocketoptions-callback"><code>dgram.createSocket(options[, callback])</code></a></li> 368<li><a href="#dgramcreatesockettype-callback"><code>dgram.createSocket(type[, callback])</code></a></li> 369</ul> 370</li> 371</ul> 372</li> 373</ul></details> 374 375 <div id="apicontent"> 376 <h2>UDP/datagram sockets<span><a class="mark" href="#udpdatagram-sockets" id="udpdatagram-sockets">#</a></span><a aria-hidden="true" class="legacy" id="dgram_udp_datagram_sockets"></a></h2> 377 378<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p> 379 380<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v18.20.1/lib/dgram.js">lib/dgram.js</a></p> 381<p>The <code>node:dgram</code> module provides an implementation of UDP datagram sockets.</p> 382 383<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>; 384 385<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 386 387server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 388 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>); 389 server.<span class="hljs-title function_">close</span>(); 390}); 391 392server.<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> { 393 <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>); 394}); 395 396server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> { 397 <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>(); 398 <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>); 399}); 400 401server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>); 402<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>); 403<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 404 405server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 406 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>); 407 server.<span class="hljs-title function_">close</span>(); 408}); 409 410server.<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> { 411 <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>); 412}); 413 414server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> { 415 <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>(); 416 <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>); 417}); 418 419server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>); 420<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><button class="copy-button">copy</button></pre> 421<section><h3>Class: <code>dgram.Socket</code><span><a class="mark" href="#class-dgramsocket" id="class-dgramsocket">#</a></span><a aria-hidden="true" class="legacy" id="dgram_class_dgram_socket"></a></h3> 422<div class="api_metadata"> 423<span>Added in: v0.1.99</span> 424</div> 425<ul> 426<li>Extends: <a href="events.html#class-eventemitter" class="type"><EventEmitter></a></li> 427</ul> 428<p>Encapsulates the datagram functionality.</p> 429<p>New instances of <code>dgram.Socket</code> are created using <a href="#dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>. 430The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p> 431<h4>Event: <code>'close'</code><span><a class="mark" href="#event-close" id="event-close">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_close"></a></h4> 432<div class="api_metadata"> 433<span>Added in: v0.1.99</span> 434</div> 435<p>The <code>'close'</code> event is emitted after a socket is closed with <a href="#socketclosecallback"><code>close()</code></a>. 436Once triggered, no new <code>'message'</code> events will be emitted on this socket.</p> 437<h4>Event: <code>'connect'</code><span><a class="mark" href="#event-connect" id="event-connect">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_connect"></a></h4> 438<div class="api_metadata"> 439<span>Added in: v12.0.0</span> 440</div> 441<p>The <code>'connect'</code> event is emitted after a socket is associated to a remote 442address as a result of a successful <a href="#socketconnectport-address-callback"><code>connect()</code></a> call.</p> 443<h4>Event: <code>'error'</code><span><a class="mark" href="#event-error" id="event-error">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_error"></a></h4> 444<div class="api_metadata"> 445<span>Added in: v0.1.99</span> 446</div> 447<ul> 448<li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 449</ul> 450<p>The <code>'error'</code> event is emitted whenever any error occurs. The event handler 451function is passed a single <code>Error</code> object.</p> 452<h4>Event: <code>'listening'</code><span><a class="mark" href="#event-listening" id="event-listening">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_listening"></a></h4> 453<div class="api_metadata"> 454<span>Added in: v0.1.99</span> 455</div> 456<p>The <code>'listening'</code> event is emitted once the <code>dgram.Socket</code> is addressable and 457can receive data. This happens either explicitly with <code>socket.bind()</code> or 458implicitly the first time data is sent using <code>socket.send()</code>. 459Until the <code>dgram.Socket</code> is listening, the underlying system resources do not 460exist and calls such as <code>socket.address()</code> and <code>socket.setTTL()</code> will fail.</p> 461<h4>Event: <code>'message'</code><span><a class="mark" href="#event-message" id="event-message">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_message"></a></h4> 462<div class="api_metadata"> 463<details class="changelog"><summary>History</summary> 464<table> 465<tbody><tr><th>Version</th><th>Changes</th></tr> 466<tr><td>v18.4.0</td> 467<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr> 468<tr><td>v18.0.0</td> 469<td><p>The <code>family</code> property now returns a number instead of a string.</p></td></tr> 470<tr><td>v0.1.99</td> 471<td><p><span>Added in: v0.1.99</span></p></td></tr> 472</tbody></table> 473</details> 474</div> 475<p>The <code>'message'</code> event is emitted when a new datagram is available on a socket. 476The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>.</p> 477<ul> 478<li><code>msg</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> The message.</li> 479<li><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Remote address information. 480<ul> 481<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The sender address.</li> 482<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The address family (<code>'IPv4'</code> or <code>'IPv6'</code>).</li> 483<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The sender port.</li> 484<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The message size.</li> 485</ul> 486</li> 487</ul> 488<p>If the source address of the incoming packet is an IPv6 link-local 489address, the interface name is added to the <code>address</code>. For 490example, a packet received on the <code>en0</code> interface might have the 491address field set to <code>'fe80::2618:1234:ab11:3b9c%en0'</code>, where <code>'%en0'</code> 492is the interface name as a zone ID suffix.</p> 493<h4><code>socket.addMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#socketaddmembershipmulticastaddress-multicastinterface" id="socketaddmembershipmulticastaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_addmembership_multicastaddress_multicastinterface"></a></h4> 494<div class="api_metadata"> 495<span>Added in: v0.6.9</span> 496</div> 497<ul> 498<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 499<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 500</ul> 501<p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and 502<code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the 503<code>multicastInterface</code> argument is not specified, the operating system will choose 504one interface and will add membership to it. To add membership to every 505available interface, call <code>addMembership</code> multiple times, once per interface.</p> 506<p>When called on an unbound socket, this method will implicitly bind to a random 507port, listening on all interfaces.</p> 508<p>When sharing a UDP socket across multiple <code>cluster</code> workers, the 509<code>socket.addMembership()</code> function must be called only once or an 510<code>EADDRINUSE</code> error will occur:</p> 511 512<pre class="with-40-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>; 513<span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>; 514 515<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) { 516 cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span> 517 cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span> 518} <span class="hljs-keyword">else</span> { 519 <span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 520 s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> { 521 s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>); 522 }); 523}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>); 524<span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>); 525 526<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) { 527 cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span> 528 cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span> 529} <span class="hljs-keyword">else</span> { 530 <span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 531 s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> { 532 s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>); 533 }); 534}</code><button class="copy-button">copy</button></pre> 535<h4><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface" id="socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"></a></h4> 536<div class="api_metadata"> 537<span>Added in: v13.1.0, v12.16.0</span> 538</div> 539<ul> 540<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 541<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 542<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 543</ul> 544<p>Tells the kernel to join a source-specific multicast channel at the given 545<code>sourceAddress</code> and <code>groupAddress</code>, using the <code>multicastInterface</code> with the 546<code>IP_ADD_SOURCE_MEMBERSHIP</code> socket option. If the <code>multicastInterface</code> argument 547is not specified, the operating system will choose one interface and will add 548membership to it. To add membership to every available interface, call 549<code>socket.addSourceSpecificMembership()</code> multiple times, once per interface.</p> 550<p>When called on an unbound socket, this method will implicitly bind to a random 551port, listening on all interfaces.</p> 552<h4><code>socket.address()</code><span><a class="mark" href="#socketaddress" id="socketaddress">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_address"></a></h4> 553<div class="api_metadata"> 554<span>Added in: v0.1.99</span> 555</div> 556<ul> 557<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 558</ul> 559<p>Returns an object containing the address information for a socket. 560For UDP sockets, this object will contain <code>address</code>, <code>family</code>, and <code>port</code> 561properties.</p> 562<p>This method throws <code>EBADF</code> if called on an unbound socket.</p> 563<h4><code>socket.bind([port][, address][, callback])</code><span><a class="mark" href="#socketbindport-address-callback" id="socketbindport-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_bind_port_address_callback"></a></h4> 564<div class="api_metadata"> 565<details class="changelog"><summary>History</summary> 566<table> 567<tbody><tr><th>Version</th><th>Changes</th></tr> 568<tr><td>v0.9.1</td> 569<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> 570<tr><td>v0.1.99</td> 571<td><p><span>Added in: v0.1.99</span></p></td></tr> 572</tbody></table> 573</details> 574</div> 575<ul> 576<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 577<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 578<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> with no parameters. Called when binding is complete.</li> 579</ul> 580<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram 581messages on a named <code>port</code> and optional <code>address</code>. If <code>port</code> is not 582specified or is <code>0</code>, the operating system will attempt to bind to a 583random port. If <code>address</code> is not specified, the operating system will 584attempt to listen on all addresses. Once binding is complete, a 585<code>'listening'</code> event is emitted and the optional <code>callback</code> function is 586called.</p> 587<p>Specifying both a <code>'listening'</code> event listener and passing a 588<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very 589useful.</p> 590<p>A bound datagram socket keeps the Node.js process running to receive 591datagram messages.</p> 592<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g. 593attempting to bind with a closed socket), an <a href="errors.html#class-error"><code>Error</code></a> may be thrown.</p> 594<p>Example of a UDP server listening on port 41234:</p> 595 596<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>; 597 598<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 599 600server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 601 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>); 602 server.<span class="hljs-title function_">close</span>(); 603}); 604 605server.<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> { 606 <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>); 607}); 608 609server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> { 610 <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>(); 611 <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>); 612}); 613 614server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>); 615<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>); 616<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 617 618server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 619 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>); 620 server.<span class="hljs-title function_">close</span>(); 621}); 622 623server.<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> { 624 <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>); 625}); 626 627server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> { 628 <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>(); 629 <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>); 630}); 631 632server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>); 633<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><button class="copy-button">copy</button></pre> 634<h4><code>socket.bind(options[, callback])</code><span><a class="mark" href="#socketbindoptions-callback" id="socketbindoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_bind_options_callback"></a></h4> 635<div class="api_metadata"> 636<span>Added in: v0.11.14</span> 637</div> 638<ul> 639<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Required. Supports the following properties: 640<ul> 641<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 642<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 643<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 644<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 645</ul> 646</li> 647<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> 648</ul> 649<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram 650messages on a named <code>port</code> and optional <code>address</code> that are passed as 651properties of an <code>options</code> object passed as the first argument. If 652<code>port</code> is not specified or is <code>0</code>, the operating system will attempt 653to bind to a random port. If <code>address</code> is not specified, the operating 654system will attempt to listen on all addresses. Once binding is 655complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code> 656function is called.</p> 657<p>The <code>options</code> object may contain a <code>fd</code> property. When a <code>fd</code> greater 658than <code>0</code> is set, it will wrap around an existing socket with the given 659file descriptor. In this case, the properties of <code>port</code> and <code>address</code> 660will be ignored.</p> 661<p>Specifying both a <code>'listening'</code> event listener and passing a 662<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very 663useful.</p> 664<p>The <code>options</code> object may contain an additional <code>exclusive</code> property that is 665used when using <code>dgram.Socket</code> objects with the <a href="cluster.html"><code>cluster</code></a> module. When 666<code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same 667underlying socket handle allowing connection handling duties to be shared. 668When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted 669port sharing results in an error.</p> 670<p>A bound datagram socket keeps the Node.js process running to receive 671datagram messages.</p> 672<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g. 673attempting to bind with a closed socket), an <a href="errors.html#class-error"><code>Error</code></a> may be thrown.</p> 674<p>An example socket listening on an exclusive port is shown below.</p> 675<pre><code class="language-js">socket.<span class="hljs-title function_">bind</span>({ 676 <span class="hljs-attr">address</span>: <span class="hljs-string">'localhost'</span>, 677 <span class="hljs-attr">port</span>: <span class="hljs-number">8000</span>, 678 <span class="hljs-attr">exclusive</span>: <span class="hljs-literal">true</span>, 679});</code> <button class="copy-button">copy</button></pre> 680<h4><code>socket.close([callback])</code><span><a class="mark" href="#socketclosecallback" id="socketclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_close_callback"></a></h4> 681<div class="api_metadata"> 682<span>Added in: v0.1.99</span> 683</div> 684<ul> 685<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the socket has been closed.</li> 686</ul> 687<p>Close the underlying socket and stop listening for data on it. If a callback is 688provided, it is added as a listener for the <a href="#event-close"><code>'close'</code></a> event.</p> 689<h4><code>socket[Symbol.asyncDispose]()</code><span><a class="mark" href="#socketsymbolasyncdispose" id="socketsymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_symbol_asyncdispose"></a></h4> 690<div class="api_metadata"> 691<span>Added in: v18.18.0</span> 692</div> 693<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 694<p>Calls <a href="#socketclosecallback"><code>socket.close()</code></a> and returns a promise that fulfills when the 695socket has closed.</p> 696<h4><code>socket.connect(port[, address][, callback])</code><span><a class="mark" href="#socketconnectport-address-callback" id="socketconnectport-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_connect_port_address_callback"></a></h4> 697<div class="api_metadata"> 698<span>Added in: v12.0.0</span> 699</div> 700<ul> 701<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 702<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 703<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the connection is completed or on error.</li> 704</ul> 705<p>Associates the <code>dgram.Socket</code> to a remote address and port. Every 706message sent by this handle is automatically sent to that destination. Also, 707the socket will only receive messages from that remote peer. 708Trying to call <code>connect()</code> on an already connected socket will result 709in an <a href="errors.html#err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a> exception. If <code>address</code> is not 710provided, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code> (for <code>udp6</code> sockets) 711will be used by default. Once the connection is complete, a <code>'connect'</code> event 712is emitted and the optional <code>callback</code> function is called. In case of failure, 713the <code>callback</code> is called or, failing this, an <code>'error'</code> event is emitted.</p> 714<h4><code>socket.disconnect()</code><span><a class="mark" href="#socketdisconnect" id="socketdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_disconnect"></a></h4> 715<div class="api_metadata"> 716<span>Added in: v12.0.0</span> 717</div> 718<p>A synchronous function that disassociates a connected <code>dgram.Socket</code> from 719its remote address. Trying to call <code>disconnect()</code> on an unbound or already 720disconnected socket will result in an <a href="errors.html#err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> 721exception.</p> 722<h4><code>socket.dropMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#socketdropmembershipmulticastaddress-multicastinterface" id="socketdropmembershipmulticastaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_dropmembership_multicastaddress_multicastinterface"></a></h4> 723<div class="api_metadata"> 724<span>Added in: v0.6.9</span> 725</div> 726<ul> 727<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 728<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 729</ul> 730<p>Instructs the kernel to leave a multicast group at <code>multicastAddress</code> using the 731<code>IP_DROP_MEMBERSHIP</code> socket option. This method is automatically called by the 732kernel when the socket is closed or the process terminates, so most apps will 733never have reason to call this.</p> 734<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to 735drop membership on all valid interfaces.</p> 736<h4><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface" id="socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"></a></h4> 737<div class="api_metadata"> 738<span>Added in: v13.1.0, v12.16.0</span> 739</div> 740<ul> 741<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 742<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 743<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 744</ul> 745<p>Instructs the kernel to leave a source-specific multicast channel at the given 746<code>sourceAddress</code> and <code>groupAddress</code> using the <code>IP_DROP_SOURCE_MEMBERSHIP</code> 747socket option. This method is automatically called by the kernel when the 748socket is closed or the process terminates, so most apps will never have 749reason to call this.</p> 750<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to 751drop membership on all valid interfaces.</p> 752<h4><code>socket.getRecvBufferSize()</code><span><a class="mark" href="#socketgetrecvbuffersize" id="socketgetrecvbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getrecvbuffersize"></a></h4> 753<div class="api_metadata"> 754<span>Added in: v8.7.0</span> 755</div> 756<ul> 757<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the <code>SO_RCVBUF</code> socket receive buffer size in bytes.</li> 758</ul> 759<p>This method throws <a href="errors.html#err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p> 760<h4><code>socket.getSendBufferSize()</code><span><a class="mark" href="#socketgetsendbuffersize" id="socketgetsendbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendbuffersize"></a></h4> 761<div class="api_metadata"> 762<span>Added in: v8.7.0</span> 763</div> 764<ul> 765<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the <code>SO_SNDBUF</code> socket send buffer size in bytes.</li> 766</ul> 767<p>This method throws <a href="errors.html#err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p> 768<h4><code>socket.getSendQueueSize()</code><span><a class="mark" href="#socketgetsendqueuesize" id="socketgetsendqueuesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendqueuesize"></a></h4> 769<div class="api_metadata"> 770<span>Added in: v18.8.0</span> 771</div> 772<ul> 773<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of bytes queued for sending.</li> 774</ul> 775<h4><code>socket.getSendQueueCount()</code><span><a class="mark" href="#socketgetsendqueuecount" id="socketgetsendqueuecount">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendqueuecount"></a></h4> 776<div class="api_metadata"> 777<span>Added in: v18.8.0</span> 778</div> 779<ul> 780<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of send requests currently in the queue awaiting 781to be processed.</li> 782</ul> 783<h4><code>socket.ref()</code><span><a class="mark" href="#socketref" id="socketref">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_ref"></a></h4> 784<div class="api_metadata"> 785<span>Added in: v0.9.1</span> 786</div> 787<ul> 788<li>Returns: <a href="dgram.html#class-dgramsocket" class="type"><dgram.Socket></a></li> 789</ul> 790<p>By default, binding a socket will cause it to block the Node.js process from 791exiting as long as the socket is open. The <code>socket.unref()</code> method can be used 792to exclude the socket from the reference counting that keeps the Node.js 793process active. The <code>socket.ref()</code> method adds the socket back to the reference 794counting and restores the default behavior.</p> 795<p>Calling <code>socket.ref()</code> multiples times will have no additional effect.</p> 796<p>The <code>socket.ref()</code> method returns a reference to the socket so calls can be 797chained.</p> 798<h4><code>socket.remoteAddress()</code><span><a class="mark" href="#socketremoteaddress" id="socketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_remoteaddress"></a></h4> 799<div class="api_metadata"> 800<span>Added in: v12.0.0</span> 801</div> 802<ul> 803<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 804</ul> 805<p>Returns an object containing the <code>address</code>, <code>family</code>, and <code>port</code> of the remote 806endpoint. This method throws an <a href="errors.html#err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> exception 807if the socket is not connected.</p> 808<h4><code>socket.send(msg[, offset, length][, port][, address][, callback])</code><span><a class="mark" href="#socketsendmsg-offset-length-port-address-callback" id="socketsendmsg-offset-length-port-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_send_msg_offset_length_port_address_callback"></a></h4> 809<div class="api_metadata"> 810<details class="changelog"><summary>History</summary> 811<table> 812<tbody><tr><th>Version</th><th>Changes</th></tr> 813<tr><td>v17.0.0</td> 814<td><p>The <code>address</code> parameter now only accepts a <code>string</code>, <code>null</code> or <code>undefined</code>.</p></td></tr> 815<tr><td>v14.5.0, v12.19.0</td> 816<td><p>The <code>msg</code> parameter can now be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> 817<tr><td>v12.0.0</td> 818<td><p>Added support for sending data on connected sockets.</p></td></tr> 819<tr><td>v8.0.0</td> 820<td><p>The <code>msg</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> 821<tr><td>v8.0.0</td> 822<td><p>The <code>address</code> parameter is always optional now.</p></td></tr> 823<tr><td>v6.0.0</td> 824<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> 825<tr><td>v5.7.0</td> 826<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> 827<tr><td>v0.1.99</td> 828<td><p><span>Added in: v0.1.99</span></p></td></tr> 829</tbody></table> 830</details> 831</div> 832<ul> 833<li><code>msg</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Message to be sent.</li> 834<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Offset in the buffer where the message starts.</li> 835<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes in the message.</li> 836<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Destination port.</li> 837<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Destination host name or IP address.</li> 838<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the message has been sent.</li> 839</ul> 840<p>Broadcasts a datagram on the socket. 841For connectionless sockets, the destination <code>port</code> and <code>address</code> must be 842specified. Connected sockets, on the other hand, will use their associated 843remote endpoint, so the <code>port</code> and <code>address</code> arguments must not be set.</p> 844<p>The <code>msg</code> argument contains the message to be sent. 845Depending on its type, different behavior can apply. If <code>msg</code> is a <code>Buffer</code>, 846any <code>TypedArray</code> or a <code>DataView</code>, 847the <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the 848message begins and the number of bytes in the message, respectively. 849If <code>msg</code> is a <code>String</code>, then it is automatically converted to a <code>Buffer</code> 850with <code>'utf8'</code> encoding. With messages that 851contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with 852respect to <a href="buffer.html#static-method-bufferbytelengthstring-encoding">byte length</a> and not the character position. 853If <code>msg</code> is an array, <code>offset</code> and <code>length</code> must not be specified.</p> 854<p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name, 855DNS will be used to resolve the address of the host. If <code>address</code> is not 856provided or otherwise nullish, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code> 857(for <code>udp6</code> sockets) will be used by default.</p> 858<p>If the socket has not been previously bound with a call to <code>bind</code>, the socket 859is assigned a random port number and is bound to the "all interfaces" address 860(<code>'0.0.0.0'</code> for <code>udp4</code> sockets, <code>'::0'</code> for <code>udp6</code> sockets.)</p> 861<p>An optional <code>callback</code> function may be specified to as a way of reporting 862DNS errors or for determining when it is safe to reuse the <code>buf</code> object. 863DNS lookups delay the time to send for at least one tick of the 864Node.js event loop.</p> 865<p>The only way to know for sure that the datagram has been sent is by using a 866<code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be 867passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given, 868the error is emitted as an <code>'error'</code> event on the <code>socket</code> object.</p> 869<p>Offset and length are optional but both <em>must</em> be set if either are used. 870They are supported only when the first argument is a <code>Buffer</code>, a <code>TypedArray</code>, 871or a <code>DataView</code>.</p> 872<p>This method throws <a href="errors.html#err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a> if called on an unbound socket.</p> 873<p>Example of sending a UDP packet to a port on <code>localhost</code>;</p> 874 875<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>; 876<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>; 877 878<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>); 879<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 880client.<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> { 881 client.<span class="hljs-title function_">close</span>(); 882});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>); 883<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>); 884 885<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>); 886<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 887client.<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> { 888 client.<span class="hljs-title function_">close</span>(); 889});</code><button class="copy-button">copy</button></pre> 890<p>Example of sending a UDP packet composed of multiple buffers to a port on 891<code>127.0.0.1</code>;</p> 892 893<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>; 894<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>; 895 896<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>); 897<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>); 898<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 899client.<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> { 900 client.<span class="hljs-title function_">close</span>(); 901});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>); 902<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>); 903 904<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>); 905<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>); 906<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 907client.<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> { 908 client.<span class="hljs-title function_">close</span>(); 909});</code><button class="copy-button">copy</button></pre> 910<p>Sending multiple buffers might be faster or slower depending on the 911application and operating system. Run benchmarks to 912determine the optimal strategy on a case-by-case basis. Generally speaking, 913however, sending multiple buffers is faster.</p> 914<p>Example of sending a UDP packet using a socket connected to a port on 915<code>localhost</code>:</p> 916 917<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>; 918<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>; 919 920<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>); 921<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 922client.<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> { 923 client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 924 client.<span class="hljs-title function_">close</span>(); 925 }); 926});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>); 927<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>); 928 929<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>); 930<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>); 931client.<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> { 932 client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 933 client.<span class="hljs-title function_">close</span>(); 934 }); 935});</code><button class="copy-button">copy</button></pre> 936<h5>Note about UDP datagram size<span><a class="mark" href="#note-about-udp-datagram-size" id="note-about-udp-datagram-size">#</a></span><a aria-hidden="true" class="legacy" id="dgram_note_about_udp_datagram_size"></a></h5> 937<p>The maximum size of an IPv4/v6 datagram depends on the <code>MTU</code> 938(Maximum Transmission Unit) and on the <code>Payload Length</code> field size.</p> 939<ul> 940<li> 941<p>The <code>Payload Length</code> field is 16 bits wide, which means that a normal 942payload cannot exceed 64K octets including the internet header and data 943(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); 944this is generally true for loopback interfaces, but such long datagram 945messages are impractical for most hosts and networks.</p> 946</li> 947<li> 948<p>The <code>MTU</code> is the largest size a given link layer technology can support for 949datagram messages. For any link, IPv4 mandates a minimum <code>MTU</code> of 68 950octets, while the recommended <code>MTU</code> for IPv4 is 576 (typically recommended 951as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in 952fragments.</p> 953<p>For IPv6, the minimum <code>MTU</code> is 1280 octets. However, the mandatory minimum 954fragment reassembly buffer size is 1500 octets. The value of 68 octets is 955very small, since most current link layer technologies, like Ethernet, have a 956minimum <code>MTU</code> of 1500.</p> 957</li> 958</ul> 959<p>It is impossible to know in advance the MTU of each link through which 960a packet might travel. Sending a datagram greater than the receiver <code>MTU</code> will 961not work because the packet will get silently dropped without informing the 962source that the data did not reach its intended recipient.</p> 963<h4><code>socket.setBroadcast(flag)</code><span><a class="mark" href="#socketsetbroadcastflag" id="socketsetbroadcastflag">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setbroadcast_flag"></a></h4> 964<div class="api_metadata"> 965<span>Added in: v0.6.9</span> 966</div> 967<ul> 968<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 969</ul> 970<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When set to <code>true</code>, UDP 971packets may be sent to a local interface's broadcast address.</p> 972<p>This method throws <code>EBADF</code> if called on an unbound socket.</p> 973<h4><code>socket.setMulticastInterface(multicastInterface)</code><span><a class="mark" href="#socketsetmulticastinterfacemulticastinterface" id="socketsetmulticastinterfacemulticastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastinterface_multicastinterface"></a></h4> 974<div class="api_metadata"> 975<span>Added in: v8.6.0</span> 976</div> 977<ul> 978<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 979</ul> 980<p><em>All references to scope in this section are referring to 981<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 982with a scope index is written as <code>'IP%scope'</code> where scope is an interface name 983or interface number.</em></p> 984<p>Sets the default outgoing multicast interface of the socket to a chosen 985interface or back to system interface selection. The <code>multicastInterface</code> must 986be a valid string representation of an IP from the socket's family.</p> 987<p>For IPv4 sockets, this should be the IP configured for the desired physical 988interface. All packets sent to multicast on the socket will be sent on the 989interface determined by the most recent successful use of this call.</p> 990<p>For IPv6 sockets, <code>multicastInterface</code> should include a scope to indicate the 991interface as in the examples that follow. In IPv6, individual <code>send</code> calls can 992also use explicit scope in addresses, so only packets sent to a multicast 993address without specifying an explicit scope are affected by the most recent 994successful use of this call.</p> 995<p>This method throws <code>EBADF</code> if called on an unbound socket.</p> 996<h5>Example: IPv6 outgoing multicast interface<span><a class="mark" href="#example-ipv6-outgoing-multicast-interface" id="example-ipv6-outgoing-multicast-interface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_example_ipv6_outgoing_multicast_interface"></a></h5> 997<p>On most systems, where scope format uses the interface name:</p> 998<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>); 999 1000socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> { 1001 socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%eth1'</span>); 1002});</code> <button class="copy-button">copy</button></pre> 1003<p>On Windows, where scope format uses an interface number:</p> 1004<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>); 1005 1006socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> { 1007 socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%2'</span>); 1008});</code> <button class="copy-button">copy</button></pre> 1009<h5>Example: IPv4 outgoing multicast interface<span><a class="mark" href="#example-ipv4-outgoing-multicast-interface" id="example-ipv4-outgoing-multicast-interface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_example_ipv4_outgoing_multicast_interface"></a></h5> 1010<p>All systems use an IP of the host on the desired physical interface:</p> 1011<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>); 1012 1013socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> { 1014 socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'10.0.0.2'</span>); 1015});</code> <button class="copy-button">copy</button></pre> 1016<h5>Call results<span><a class="mark" href="#call-results" id="call-results">#</a></span><a aria-hidden="true" class="legacy" id="dgram_call_results"></a></h5> 1017<p>A call on a socket that is not ready to send or no longer open may throw a <em>Not 1018running</em> <a href="errors.html#class-error"><code>Error</code></a>.</p> 1019<p>If <code>multicastInterface</code> can not be parsed into an IP then an <em>EINVAL</em> 1020<a href="errors.html#class-systemerror"><code>System Error</code></a> is thrown.</p> 1021<p>On IPv4, if <code>multicastInterface</code> is a valid address but does not match any 1022interface, or if the address does not match the family then 1023a <a href="errors.html#class-systemerror"><code>System Error</code></a> such as <code>EADDRNOTAVAIL</code> or <code>EPROTONOSUP</code> is thrown.</p> 1024<p>On IPv6, most errors with specifying or omitting scope will result in the socket 1025continuing to use (or returning to) the system's default interface selection.</p> 1026<p>A socket's address family's ANY address (IPv4 <code>'0.0.0.0'</code> or IPv6 <code>'::'</code>) can be 1027used to return control of the sockets default outgoing interface to the system 1028for future multicast packets.</p> 1029<h4><code>socket.setMulticastLoopback(flag)</code><span><a class="mark" href="#socketsetmulticastloopbackflag" id="socketsetmulticastloopbackflag">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastloopback_flag"></a></h4> 1030<div class="api_metadata"> 1031<span>Added in: v0.3.8</span> 1032</div> 1033<ul> 1034<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1035</ul> 1036<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When set to <code>true</code>, 1037multicast packets will also be received on the local interface.</p> 1038<p>This method throws <code>EBADF</code> if called on an unbound socket.</p> 1039<h4><code>socket.setMulticastTTL(ttl)</code><span><a class="mark" href="#socketsetmulticastttlttl" id="socketsetmulticastttlttl">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastttl_ttl"></a></h4> 1040<div class="api_metadata"> 1041<span>Added in: v0.3.8</span> 1042</div> 1043<ul> 1044<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1045</ul> 1046<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. While TTL generally stands for 1047"Time to Live", in this context it specifies the number of IP hops that a 1048packet is allowed to travel through, specifically for multicast traffic. Each 1049router or gateway that forwards a packet decrements the TTL. If the TTL is 1050decremented to 0 by a router, it will not be forwarded.</p> 1051<p>The <code>ttl</code> argument may be between 0 and 255. The default on most systems is <code>1</code>.</p> 1052<p>This method throws <code>EBADF</code> if called on an unbound socket.</p> 1053<h4><code>socket.setRecvBufferSize(size)</code><span><a class="mark" href="#socketsetrecvbuffersizesize" id="socketsetrecvbuffersizesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setrecvbuffersize_size"></a></h4> 1054<div class="api_metadata"> 1055<span>Added in: v8.7.0</span> 1056</div> 1057<ul> 1058<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1059</ul> 1060<p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer 1061in bytes.</p> 1062<p>This method throws <a href="errors.html#err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p> 1063<h4><code>socket.setSendBufferSize(size)</code><span><a class="mark" href="#socketsetsendbuffersizesize" id="socketsetsendbuffersizesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setsendbuffersize_size"></a></h4> 1064<div class="api_metadata"> 1065<span>Added in: v8.7.0</span> 1066</div> 1067<ul> 1068<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1069</ul> 1070<p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer 1071in bytes.</p> 1072<p>This method throws <a href="errors.html#err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p> 1073<h4><code>socket.setTTL(ttl)</code><span><a class="mark" href="#socketsetttlttl" id="socketsetttlttl">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setttl_ttl"></a></h4> 1074<div class="api_metadata"> 1075<span>Added in: v0.1.101</span> 1076</div> 1077<ul> 1078<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1079</ul> 1080<p>Sets the <code>IP_TTL</code> socket option. While TTL generally stands for "Time to Live", 1081in this context it specifies the number of IP hops that a packet is allowed to 1082travel through. Each router or gateway that forwards a packet decrements the 1083TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. 1084Changing TTL values is typically done for network probes or when multicasting.</p> 1085<p>The <code>ttl</code> argument may be between 1 and 255. The default on most systems 1086is 64.</p> 1087<p>This method throws <code>EBADF</code> if called on an unbound socket.</p> 1088<h4><code>socket.unref()</code><span><a class="mark" href="#socketunref" id="socketunref">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_unref"></a></h4> 1089<div class="api_metadata"> 1090<span>Added in: v0.9.1</span> 1091</div> 1092<ul> 1093<li>Returns: <a href="dgram.html#class-dgramsocket" class="type"><dgram.Socket></a></li> 1094</ul> 1095<p>By default, binding a socket will cause it to block the Node.js process from 1096exiting as long as the socket is open. The <code>socket.unref()</code> method can be used 1097to exclude the socket from the reference counting that keeps the Node.js 1098process active, allowing the process to exit even if the socket is still 1099listening.</p> 1100<p>Calling <code>socket.unref()</code> multiple times will have no addition effect.</p> 1101<p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be 1102chained.</p> 1103</section><section><h3><code>node:dgram</code> module functions<span><a class="mark" href="#nodedgram-module-functions" id="nodedgram-module-functions">#</a></span><a aria-hidden="true" class="legacy" id="dgram_node_dgram_module_functions"></a></h3> 1104<h4><code>dgram.createSocket(options[, callback])</code><span><a class="mark" href="#dgramcreatesocketoptions-callback" id="dgramcreatesocketoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_dgram_createsocket_options_callback"></a></h4> 1105<div class="api_metadata"> 1106<details class="changelog"><summary>History</summary> 1107<table> 1108<tbody><tr><th>Version</th><th>Changes</th></tr> 1109<tr><td>v15.8.0</td> 1110<td><p>AbortSignal support was added.</p></td></tr> 1111<tr><td>v11.4.0</td> 1112<td><p>The <code>ipv6Only</code> option is supported.</p></td></tr> 1113<tr><td>v8.7.0</td> 1114<td><p>The <code>recvBufferSize</code> and <code>sendBufferSize</code> options are supported now.</p></td></tr> 1115<tr><td>v8.6.0</td> 1116<td><p>The <code>lookup</code> option is supported.</p></td></tr> 1117<tr><td>v0.11.13</td> 1118<td><p><span>Added in: v0.11.13</span></p></td></tr> 1119</tbody></table> 1120</details> 1121</div> 1122<ul> 1123<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Available options are: 1124<ul> 1125<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The family of socket. Must be either <code>'udp4'</code> or <code>'udp6'</code>. 1126Required.</li> 1127<li><code>reuseAddr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> <a href="#socketbindport-address-callback"><code>socket.bind()</code></a> will reuse the 1128address, even if another process has already bound a socket on it. 1129<strong>Default:</strong> <code>false</code>.</li> 1130<li><code>ipv6Only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Setting <code>ipv6Only</code> to <code>true</code> will 1131disable dual-stack support, i.e., binding to address <code>::</code> won't make 1132<code>0.0.0.0</code> be bound. <strong>Default:</strong> <code>false</code>.</li> 1133<li><code>recvBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the <code>SO_RCVBUF</code> socket value.</li> 1134<li><code>sendBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the <code>SO_SNDBUF</code> socket value.</li> 1135<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="dns.html#dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li> 1136<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> An AbortSignal that may be used to close a socket.</li> 1137</ul> 1138</li> 1139<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Attached as a listener for <code>'message'</code> events. Optional.</li> 1140<li>Returns: <a href="dgram.html#class-dgramsocket" class="type"><dgram.Socket></a></li> 1141</ul> 1142<p>Creates a <code>dgram.Socket</code> object. Once the socket is created, calling 1143<a href="#socketbindport-address-callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram 1144messages. When <code>address</code> and <code>port</code> are not passed to <a href="#socketbindport-address-callback"><code>socket.bind()</code></a> the 1145method will bind the socket to the "all interfaces" address on a random port 1146(it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address 1147and port can be retrieved using <a href="#socketaddress"><code>socket.address().address</code></a> and 1148<a href="#socketaddress"><code>socket.address().port</code></a>.</p> 1149<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding 1150<code>AbortController</code> is similar to calling <code>.close()</code> on the socket:</p> 1151<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>(); 1152<span class="hljs-keyword">const</span> { signal } = controller; 1153<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 }); 1154server.<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> { 1155 <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>); 1156}); 1157<span class="hljs-comment">// Later, when you want to close the server.</span> 1158controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 1159<h4><code>dgram.createSocket(type[, callback])</code><span><a class="mark" href="#dgramcreatesockettype-callback" id="dgramcreatesockettype-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_dgram_createsocket_type_callback"></a></h4> 1160<div class="api_metadata"> 1161<span>Added in: v0.1.99</span> 1162</div> 1163<ul> 1164<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'udp4'</code> or <code>'udp6'</code>.</li> 1165<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Attached as a listener to <code>'message'</code> events.</li> 1166<li>Returns: <a href="dgram.html#class-dgramsocket" class="type"><dgram.Socket></a></li> 1167</ul> 1168<p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>.</p> 1169<p>Once the socket is created, calling <a href="#socketbindport-address-callback"><code>socket.bind()</code></a> will instruct the 1170socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are 1171not passed to <a href="#socketbindport-address-callback"><code>socket.bind()</code></a> the method will bind the socket to the "all 1172interfaces" address on a random port (it does the right thing for both <code>udp4</code> 1173and <code>udp6</code> sockets). The bound address and port can be retrieved using 1174<a href="#socketaddress"><code>socket.address().address</code></a> and <a href="#socketaddress"><code>socket.address().port</code></a>.</p></section> 1175 <!-- API END --> 1176 </div> 1177 </div> 1178 </div> 1179</body> 1180</html> 1181