KiYugadgeter
KiYugadgeter

Reputation: 4012

Web server not sending response

I am trying to write a simple HTTP client program using raw sockets in Python 3. However, the server does not return a response despite having been sent a simple HTTP request. My question is why the server doesn't return a response.

Here is my code:

from socket import *

BUF_LEN = 8192 * 100000

info = getaddrinfo('google.com', 80, AF_INET)
addr = info[-1][-1]
print(addr)

client = socket(AF_INET, SOCK_STREAM)

client.connect(addr)

client.send(b"GET /index.html HTTP1.1\r\nHost: www.google.com\r\n")
print(client.recv(BUF_LEN).decode("utf-8")) # print nothing

Upvotes: 0

Views: 769

Answers (1)

Spacedman
Spacedman

Reputation: 94317

You've missed a blank line at the end and mis-specified the HTTP version without a slash:

>>> client.send(b"GET /index.html HTTP1.1\r\nHost: www.google.com\r\n")

Should be:

>>> client.send(b"GET /index.html HTTP/1.1\r\nHost: www.google.com\r\n\r\n")
50
>>> client.recv(BUF_LEN).decode("utf-8")
u'HTTP/1.1 302 Found\r\nCache-Control: private\r\nContent-Type: text/html; charset=UTF-8\r\nLocation: http://www.google.co.uk/index.html?gfe_rd=cr&ei=fIR7WJ7QGejv8AeZzbWgCw\r\nContent-Length: 271\r\nDate: Sun, 15 Jan 2017 14:17:32 GMT\r\n\r\n<HTML><HEAD><meta http-equiv....

The blank line tells the server its the end of the headers, and since this is a GET request there's no payload and so it can then return the content.

Without the / in the HTTP/1.1 spec Google's servers will return an Error: 400 Bad Request response.

Upvotes: 2

Related Questions