无法使用 Python httplib 访问 IP



我无法使用主机的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

如果我将addr var更改为google.com,我会得到200的响应。我做错了什么?

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

对于HTTP请求,我推荐使用请求库。与httplib相比,它更高级,用户友好,并且可以轻松设置代理:

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})

最新更新