class

net.BoundSocket

class BoundSocket

Allows for the synchronous creation of a pre-bound socket, that can be passed to listen() or new net.Socket() later on. For listen() this enables synchronous port reservation, while for new net.Socket(), it allows control over the local egress port/IP, via bind(2) semantics.

Adoption transfers ownership of the socket; afterwards address() and close() throw ERR_SOCKET_HANDLE_ADOPTED. A handle that is never adopted must be closed to avoid leaking the socket.

import net from 'node:net';

const bound = new net.BoundSocket();
const { port } = bound.address();
console.log(`Reserved port ${port} for server`);

const server = net.createServer();
server.listen(bound); // Adopt as a server, or pass to new net.Socket() instead.
  • Closes the handle if it has not been adopted or closed; otherwise a no-op.

  • Returns the bound local address. When bound with port: 0, port is the OS-assigned ephemeral port.

    @returns

    An object with address, family, and port properties, as server.address() returns.

  • close(): void;

    Releases the bound socket. Only needed when the handle is never adopted.

  • fd(): number;

    Returns the file descriptor of the bound socket. Ownership remains with the BoundSocket, so the descriptor must not be closed by the caller. The descriptor is only available before the handle is adopted; afterwards it belongs to the adopting net.Server or net.Socket and fd() throws ERR_SOCKET_HANDLE_ADOPTED.

    @returns

    The underlying OS file descriptor, or -1 on platforms that do not expose one for sockets (such as Windows).