{"record":{"id":"529d1664c78493d7","repo":"python/cpython","slug":"a-stream-socket-was-expected-got-sock-r","errorCode":null,"errorMessage":"A Stream Socket was expected, got {sock!r}","messagePattern":"A Stream Socket was expected, got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Lib/asyncio/base_events.py","lineNumber":1201,"sourceCode":"                            ', '.join(str(exc) for exc in exceptions)))\n                    else:\n                        # No exceptions were collected, raise a timeout error\n                        raise TimeoutError('create_connection failed')\n                finally:\n                    exceptions = None\n\n        else:\n            if sock is None:\n                raise ValueError(\n                    'host and port was not specified and no sock specified')\n            if sock.type != socket.SOCK_STREAM:\n                # We allow AF_INET, AF_INET6, AF_UNIX as long as they\n                # are SOCK_STREAM.\n                # We support passing AF_UNIX sockets even though we have\n                # a dedicated API for that: create_unix_connection.\n                # Disallowing AF_UNIX in this method, breaks backwards\n                # compatibility.\n                raise ValueError(\n                    f'A Stream Socket was expected, got {sock!r}')\n\n        transport, protocol = await self._create_connection_transport(\n            sock, protocol_factory, ssl, server_hostname,\n            ssl_handshake_timeout=ssl_handshake_timeout,\n            ssl_shutdown_timeout=ssl_shutdown_timeout)\n        if self._debug:\n            # Get the socket from the transport because SSL transport closes\n            # the old socket and creates a new SSL socket\n            sock = transport.get_extra_info('socket')\n            logger.debug(\"%r connected to %s:%r: (%r, %r)\",\n                         sock, host, port, transport, protocol)\n        return transport, protocol\n\n    async def _create_connection_transport(\n            self, sock, protocol_factory, ssl,\n            server_hostname, server_side=False,\n            ssl_handshake_timeout=None,","sourceCodeStart":1183,"sourceCodeEnd":1219,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/asyncio/base_events.py#L1183-L1219","documentation":"Raised by create_connection's sock branch when the supplied socket is not of type SOCK_STREAM. asyncio's TCP path (and its historical AF_UNIX tolerance) requires a stream socket; datagram, raw, or packet sockets cannot back a streaming transport, so it rejects them with a ValueError naming the socket.","triggerScenarios":"loop.create_connection(proto, None, None, sock=s) where s was created with socket.SOCK_DGRAM or SOCK_RAW. Also sockets typed with flags that change the effective type check (e.g. SOCK_NONBLOCK is fine, but SOCK_DGRAM is not).","commonSituations":"Copy-pasted socket setup from a UDP code path; test doubles that fabricate sockets with the wrong type; passing a packet socket intended for a custom protocol into asyncio's stream machinery.","solutions":["Create the socket as SOCK_STREAM: socket.socket(socket.AF_INET, socket.SOCK_STREAM).","For datagram needs use loop.create_datagram_endpoint instead of create_connection.","For AF_UNIX streams prefer loop.create_unix_connection."],"exampleFix":"// before\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nawait loop.create_connection(proto, None, None, sock=sock)\n\n// after\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nawait loop.sock_connect(sock, addr)\ntransport, proto = await loop.create_connection(\n    proto, None, None, sock=sock)","handlingStrategy":"type-guard","validationCode":"if sock is not None and sock.type != socket.SOCK_STREAM:\n    raise ConfigError(f'expected SOCK_STREAM, got type {sock.type}')","typeGuard":"import socket\n\ndef is_stream_socket(sock: socket.socket) -> bool:\n    return (sock.type & socket.SOCK_STREAM) == socket.SOCK_STREAM","tryCatchPattern":null,"preventionTips":["Create sockets with SOCK_STREAM for create_connection; use create_datagram_endpoint for UDP.","Centralize socket creation in one factory so the type is never wrong by accident.","Log sock.type when adopting external sockets to catch mismatches early."],"tags":["asyncio","sockets","validation","network"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}