0

I'm working on a simple project involving sockets. Kinda like telnet. I just want it to connect to port 80 and execute GET / Here is what I'm trying:


import socket
size = 100000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "localhost"
port = 80
s.connect((host, port))
stuff = "GET /"
s.send(stuff)
r = s.recv(size)
print(r)
I run it, it connects but I don't get the output of GET /

1
  • Have you tried GET / HTTP/1.1? RFC2616 seems to require the protocol version in the Request-Line Commented Mar 1, 2011 at 21:43

3 Answers 3

2

The HTTP spec says that you need two newlines ('\r\n' * 2) after the header. Try:

stuff = 'GET /\r\n\r\n'
Sign up to request clarification or add additional context in comments.

Comments

1

You need at least a blank line after the GET /, so use stuff = "GET /\n\n". Read this example.

Comments

1

your main problem is lacking a newline after "GET /". The HTTP protocol demands a newline, so the server is waiting for it, which is why you're waiting for a response.

(A minor problem is that your buffer size is too large, the Python socket module recommends a small power of 2 like 4096.)

I suggest:

import socket
size = 4096
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "localhost"
port = 80
s.connect((host, port))
stuff = "GET /\n"
s.send(stuff)
buf = ''
while True:
    r = s.recv(size)
    if not r: break
    buf += r

print(buf)

The loop at the end assures you'll get the entire response.

And finally, I recommend urllib2, which implements HTTP for you and avoids such bugs:

import urllib2
print(urllib2.urlopen('http://localhost').read())

Comments

Your Answer

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.