denoland/deno · error · Error

ERR_SOCKET_DGRAM_IS_CONNECTED

ERR_SOCKET_DGRAM_IS_CONNECTED

Error message

Already connected

What it means

Socket.connect() requires the socket to be in the CONNECT_STATE_DISCONNECTED state; if a previous connect is still in flight (CONNECTING) or already established (CONNECTED), a second connect throws ERR_SOCKET_DGRAM_IS_CONNECTED. A UDP socket has at most one connected peer at a time.

Source

Thrown at ext/node/polyfills/dgram.ts:614

    callback?: (err?: ErrnoException) => void,
  ): void;
  connect(port: number, callback: (err?: ErrnoException) => void): void;
  connect(port: number, address?: unknown, callback?: unknown) {
    port = validatePort(port, "Port", false);

    if (typeof address === "function") {
      callback = address;
      address = "";
    } else if (address === undefined) {
      address = "";
    }

    validateString(address, "address");

    const state = this[kStateSymbol];

    if (state.connectState !== CONNECT_STATE_DISCONNECTED) {
      throw new ERR_SOCKET_DGRAM_IS_CONNECTED();
    }

    state.connectState = CONNECT_STATE_CONNECTING;

    if (state.bindState === BIND_STATE_UNBOUND) {
      // deno-lint-ignore deno-internal/prefer-primordials -- Socket's own bind method, not Function.prototype.bind
      this.bind({ port: 0, exclusive: true });
    }

    if (state.bindState !== BIND_STATE_BOUND) {
      enqueue(
        this,
        FunctionPrototypeBind(
          _connect,
          this,
          port,
          address as string,
          callback as (err?: ErrnoException) => void,

View on GitHub (pinned to 89f33cbef2)

Solutions

  1. Call disconnect() before connecting to a new peer
  2. Track connected state in app code and skip redundant connects
  3. Use a fresh socket per peer, or use send() with explicit addresses for multiple peers

Example fix

// before
sock.connect(PORT, HOST);
sock.connect(PORT2, HOST2); // throws
// after
sock.disconnect();
sock.connect(PORT2, HOST2);
Defensive patterns

Strategy: validation

Validate before calling

function connectTo(sock, port, host) {
  try { sock.remoteAddress(); sock.disconnect(); } catch { /* not connected */ }
  sock.connect(port, host);
}

Try / catch

try { sock.connect(port, host); }
catch (e) {
  if (e.code === "ERR_SOCKET_DGRAM_IS_CONNECTED") {
    sock.disconnect();
    sock.connect(port, host);
  } else throw e;
}

Prevention

When it happens

Trigger: s.connect(port, host) called twice without disconnect(); reconnect logic that connects to a new peer without disconnecting first; racing concurrent connect calls (the second sees CONNECTING and throws).

Common situations: Reconnect wrappers copied from TCP code; connecting in a loop on timeout; multiple modules each connecting the same shared socket.

Related errors


AI-assisted analysis of denoland/deno@89f33cbef2 (2026-08-16). Data as JSON: /api/errors/0348a5bc2761d1b8. Report an issue: GitHub.