Home > Blockchain >  Why am I getting socket.gaierror?
Why am I getting socket.gaierror?

Time:06-30

I'm trying to access and show data from http://data.pr4e.org/romeo.txt . Here's my code:

import socket         
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
mysock.connect(('data.pr4e', 80))  
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()
mysock.send(cmd)    

while True:
    data = mysock.recv(512)
    if (len(data) < 1):
        break       
    print(data.decode()) 
mysock.close()

I'm getting this error message :

socket.gaierror: [Errno 11001] getaddrinfo failed. 

I saw on another question that this means I do not have a valid host name, but I'm not sure why the host name is invalid.

CodePudding user response:

The error is because you are passing the wrong host name to connect(). You need to change 'data.pr4e' to 'data.pr4e.org'.

Also, your request data is malformed, too. You need to remove the scheme and hostname from the request, and use \r\n instead of \n.

Try this:

import socket         
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
mysock.connect(('data.pr4e.org', 80))  
cmd = 'GET /romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)    

while True:
    data = mysock.recv(512)
    if (len(data) < 1):
        break       
    print(data.decode()) 
mysock.close()
  • Related