python network_error ai_generated true

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host example.com:80 ssl:default [Connection refused]

ID: python/aiohttp-client-connector-connection-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2025-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active

Root Cause

The remote host actively refused the connection, either because no service is listening on that port or a firewall blocked it.

generic

中文

远程主机主动拒绝连接,可能是因为该端口上没有服务监听,或者防火墙阻止了连接。

Workarounds

  1. 80% success Check if the service is running and the port is open
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('example.com', 80))
    if result != 0:
        print('Port is closed')
  2. 75% success Use a fallback URL or service discovery
    try:
        async with session.get('http://example.com') as resp:
            pass
    except aiohttp.ClientConnectorError:
        async with session.get('http://backup.example.com') as resp:

Dead Ends

Common approaches that don't work:

  1. Retrying with the same parameters indefinitely 50% fail

    If the service is down, retrying won't help and may waste resources.

  2. Changing the port to a common alternative without verification 60% fail

    The service may not be running on the alternative port either.