0

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
Tagc
9,1409 gold badges68 silver badges119 bronze badges
asked Jan 15, 2017 at 14:05

1 Answer 1

2

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: 2017年1月15日 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.

answered Jan 15, 2017 at 14:18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.