使用Python httplib无法达到IP

时间:2018-11-11 20:36:38

标签: python python-2.7 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

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

1 个答案:

答案 0 :(得分:0)

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

对于发出HTTP请求,我建议使用requests库。与httplib相比,它具有更高的级别和用户友好性,并且易于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})