diff --git a/doc/api/dgram.md b/doc/api/dgram.md index baeaf0e9315c8d..7cabbcbdb9ade2 100644 --- a/doc/api/dgram.md +++ b/doc/api/dgram.md @@ -447,6 +447,42 @@ will be used by default. Once the connection is complete, a `'connect'` event is emitted and the optional `callback` function is called. In case of failure, the `callback` is called or, failing this, an `'error'` event is emitted. +### `socket.connectSync(port[, address])` + + + +* `port` {integer} +* `address` {string} A numeric IP address to connect to. Unlike + [`socket.connect()`][], no DNS resolution is performed, so a host name is not + accepted. If omitted, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for + `udp6` sockets) is used. + +The synchronous counterpart of [`socket.connect()`][]. For a UDP socket +`connect(2)` only records the default peer address and is a local, non-blocking +system call, so the association is performed inline and any error such as +`ECONNREFUSED` is thrown synchronously rather than reported via the `'error'` +event: + +```js +const dgram = require('node:dgram'); + +const socket = dgram.createSocket('udp4'); +socket.connectSync(41234, '127.0.0.1'); +console.log(socket.remoteAddress()); // { address: '127.0.0.1', family: 'IPv4', port: 41234 } +``` + +If the socket is still unbound it is bound synchronously first. After +`connectSync()` returns, [`socket.remoteAddress()`][] is valid synchronously +and the `'connect'` event is emitted on the next tick. Trying to call +`connectSync()` on an already connected socket throws an +[`ERR_SOCKET_DGRAM_IS_CONNECTED`][] exception. + +`address` must be a numeric IP literal; `connectSync()` never performs DNS +resolution (asynchronous name resolution being the only genuinely blocking part +of connecting). + ### `socket.disconnect()`