开发者

Python problem with sockets

开发者 https://www.devze.com 2023-02-14 17:54 出处:网络
I\'m working on 开发者_高级运维a simple project involving sockets. Kinda like telnet. I just want it to connect to port 80 and execute GET /

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 /


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

stuff = 'GET /\r\n\r\n'


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


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())
0

精彩评论

暂无评论...
验证码 换一张
取 消