You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用HTTP协议获取网页信息遇socket.gaierror等问题求助

Fixing the socket.gaierror in your Python socket code

Hey there! Let's break down what's causing that socket.gaierror: [Errno 11001] getaddrinfo failed error and how to fix it.

The core issue

Your mistake is in the connect() call: you're passing a full URL (http://data.pr4e.org/intro-short.txt) as the host parameter, but the socket connect() method only expects the hostname (or IP address) and port number. The getaddrinfo function can't resolve URLs with the http:// prefix or file path attached, which is why you're getting that DNS resolution error—and why your telnet attempt failed too (you probably tried telnetting to the full URL instead of just the hostname).

Corrected code

Here's the fixed version of your code with the key change highlighted:

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Changed from full URL to just the hostname: data.pr4e.org
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
    data = mysock.recv(512)
    if len(data) < 1:
        break
    print(data.decode(), end='')
mysock.close()

What this fixes

  • The connect() call now targets the correct hostname (data.pr4e.org) on port 80, which getaddrinfo can resolve properly.
  • The GET request still includes the full path to the file (/intro-short.txt) as part of the HTTP command, which is exactly what the server expects.

When you run this corrected code, you should see the full HTTP response (including metadata headers like Content-Type and Content-Length) followed by the content of the intro-short.txt file.

As a side note: while using raw sockets is great for learning how HTTP works under the hood, in real-world Python code, you'd usually use libraries like requests to handle HTTP requests more cleanly. But since you're working through the Python for Everybody course, sticking with the socket approach makes perfect sense for building foundational knowledge!

内容的提问来源于stack exchange,提问作者Vishal Pallikonda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:27:01