python network_error ai_generated true

httpx.ConnectError: [Errno -2] 名称或服务未知,连接到'nonexistent.example.com'时

httpx.ConnectError: [Errno -2] Name or service not known while connecting to 'nonexistent.example.com'

ID: python/httpx-connecterror-dns-resolution-failure

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2025-02-20首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

系统DNS解析器无法解析主机名。

English

The hostname cannot be resolved by the system's DNS resolver.

generic

解决方案

  1. 85% 成功率 Use a working DNS server like Google's 8.8.8.8
    # On Linux: echo 'nameserver 8.8.8.8' > /etc/resolv.conf
    # Or use socket.create_connection with IP address
  2. 70% 成功率 Replace hostname with IP address in the request
    httpx.get('http://93.184.216.34')  # example.com IP

无效尝试

常见但无效的做法:

  1. Using a different DNS resolver in code without system changes 80% 失败

    httpx uses the system resolver by default; custom resolver requires extra setup.

  2. Ignoring the error and retrying 90% 失败

    DNS failure persists across retries.