liburl.connect cannot connect to given address – error no address associated to host name [python]

1 minute read

You are trying to connect to a web server / your server and get a URL but python is being grumpy. Host is available to your machine but python cannot view it!

You probably have two or more network interfaces. The reason that python cannot connect to given address, even though it’s reachable from your machine is that liburl does not have any option to choose which adapter to use. Unfortunately,I couldn’t find any way to use liburl or liburl2 with an option to choose network interface.

Fear not. There is a way to connect to your favorite host. Sockets! They are not as fancy and easy as liburl, but they work for good. Here is the code snippet for the impatient.

httpRequest = """
GET /index.html HTTP/1.1
Accept-Encoding: identity
Host: #Your IP Address
Connection: close
User-Agent: Python
  #Create the socket
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  #Set timeout to some seconds, 2 in this case. Don't wait forever if server doesn't respond.
  #Connect to your host
  #Send HTTP request
  #Get the response
  data = (s.recv(4096))
  #Enjoy your response!
  print data
  #Close the socket when done
except Exception, e:
  print "Error communicating with host.", sys.exc_info()[0]

Basically, you need to generate an HTTP request by yourself. It’s fairly easy and all strings. This is a basic GET request. If you already have a liburl request and working for your machine at least, you can capture the packets via Wireshark and copy the HTTP request from it, change it in code (That’s what I did actually).

Hope that helps!