{"record":{"id":"22a4923b61e91df3","repo":"python/cpython","slug":"connect-call-failed-address","errorCode":null,"errorMessage":"Connect call failed {address}","messagePattern":"Connect call failed (.+?)","errorType":"exception","errorClass":"OSError","httpStatus":null,"severity":"error","filePath":"Lib/asyncio/selector_events.py","lineNumber":687,"sourceCode":"            fut.set_exception(exc)\n        else:\n            fut.set_result(None)\n        finally:\n            fut = None\n\n    def _sock_write_done(self, fd, fut, handle=None):\n        if handle is None or not handle.cancelled():\n            self.remove_writer(fd)\n\n    def _sock_connect_cb(self, fut, sock, address):\n        if fut.done():\n            return\n\n        try:\n            err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)\n            if err != 0:\n                # Jump to any except clause below.\n                raise OSError(err, f'Connect call failed {address}')\n        except (BlockingIOError, InterruptedError):\n            # socket is still registered, the callback will be retried later\n            pass\n        except (SystemExit, KeyboardInterrupt):\n            raise\n        except BaseException as exc:\n            fut.set_exception(exc)\n        else:\n            fut.set_result(None)\n        finally:\n            fut = None\n\n    async def sock_accept(self, sock):\n        \"\"\"Accept a connection.\n\n        The socket must be bound to an address and listening for\n        connections.  The return value is a pair (conn, address) where\n        conn is a new socket object usable to send and receive data on the","sourceCodeStart":669,"sourceCodeEnd":705,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/asyncio/selector_events.py#L669-L705","documentation":"Raised as OSError(err, f'Connect call failed {address}') inside _sock_connect_cb: after a non-blocking connect completes, the callback reads the socket's SO_ERROR option, and a non-zero value means the kernel-level connection attempt failed (e.g. ECONNREFUSED, ENETUNREACH, ETIMEDOUT). The errno and target address are embedded in the message and it is delivered to the sock_connect() awaiter as the future's exception.","triggerScenarios":"await loop.sock_connect(sock, address) where the remote refuses the connection (nothing listening on the port), the host is unreachable, routing fails, or the SYN times out at the OS level.","commonSituations":"Connecting to a service that is down or started later than the client; wrong port/IP in configuration; firewall silently dropping traffic leading to timeout variants; localhost tests where the server socket is not yet bound.","solutions":["Verify the target address/port and that the remote service is listening (e.g. with ss -ltn or a manual check).","Wrap sock_connect in try/except OSError and handle ConnectionRefusedError specifically with retry-with-backoff for transient startup races.","Use asyncio.wait_for() to bound the connect attempt so kernel-level timeouts surface as asyncio timeouts you control.","Check firewall/security-group rules if connections to remote hosts consistently fail."],"exampleFix":"// before\nawait loop.sock_connect(sock, addr)  # raises OSError: [Errno 111] Connect call failed ('127.0.0.1', 8080)\n\n// after\ntry:\n    await asyncio.wait_for(loop.sock_connect(sock, addr), timeout=5)\nexcept ConnectionRefusedError:\n    log.warning(\"server at %s not ready, retrying\", addr)\n    raise","handlingStrategy":"retry","validationCode":"def can_connect(addr):\n    host, port = addr[:2]\n    try:\n        socket.getaddrinfo(host, port)\n        return True\n    except socket.gaierror:\n        return False","typeGuard":null,"tryCatchPattern":"for attempt in range(5):\n    try:\n        await asyncio.wait_for(loop.sock_connect(sock, addr), timeout=5)\n        break\n    except (ConnectionRefusedError, OSError) as e:\n        if attempt == 4:\n            raise\n        await asyncio.sleep(2 ** attempt)","preventionTips":["Wrap connect attempts in retry-with-exponential-backoff for service startup races.","Bound connects with asyncio.wait_for so failures are deterministic.","Log the address and errno from OSError to distinguish refused vs unreachable vs firewall."],"tags":["asyncio","networking","tcp","connection-refused","oserror"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}