Search code examples
pythonpython-2.7httplib

Can't reach IP using Python httplib


I can't connect to anything on my network using the IP address of the host. I can open a browser and connect and I can ping the host just fine. Here is my code:

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)

The following error gets returned:

socket.error: [Errno 51] Network is unreachable

If I change the addr var to google.com I get a 200 response. What am I doing wrong?


Solution

  • You should check the address and your proxy settings.

    For making HTTP requests I recommend the 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})