无法使用 Python httplib 访问 IP

Can't reach IP using Python httplib

我无法使用主机的 IP 地址连接到网络上的任何内容。我可以打开浏览器并连接,我可以正常 ping 主机。这是我的代码:

from httplib import HTTPConnection

addr = 192.168.14.203
conn = HTTPConnection(addr)
conn.request('HEAD', '/') 

res = conn.getresponse()

if res.status == 200:
    print "ok"
else:
    print "problem : the query returned %s because %s" % (res.status, res.reason)

返回以下错误:

socket.error: [Errno 51] Network is unreachable

如果我将地址变量更改为 google.com,我会收到 200 响应。我做错了什么?

您应该检查地址和您的代理设置。

为了发出 HTTP 请求,我推荐 requests library. It's much more high-level and user friendly compared to httplib and it makes it easy to set proxies:

import requests

addr = "http://192.168.14.203"
response = requests.get(addr)

# if you need to set a proxy:
response = requests.get(addr, proxies={"http": "...proxy address..."})

# to avoid using any proxy if your system sets one by default
response = requests.get(addr, proxies={"http": None})