Sending HTTP 1.1 GET requests with socket.send, python

Viewed 1637

I am trying to send a Get request to the google server by, GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n via Python3 sockets.send function. The code for sending is given below :

import socket
buffer = input()     #filled the with 'GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
target = "www.google.com"
port = 80
client.connect((target,port))    
client.send(buffer.encode()) 
while True:
    recv_len = 1
    response = ""
    while recv_len:
        data        = client.recv(4096).decode(errors="ignore")
        recv_len    = len(data)
        response    += data
        if recv_len < 4096:
            break
    print(response)

But I am receiving no data back from the server. Can somebody help me with this? I tried similar questions, but most are concentrated on the use of \n in the request.

1 Answers

The problem is with the line

buffer = input()

As Serge Ballesta mentioned, input() function reads \r as two characters, "\" and "r". Using

buffer = sys.stdin.read()

and piping the GET request to the program file will solve the issue.

echo -ne "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n" |python3 temp.py
Related