Socket can’t receive any data from the server, when there is a successful response, but with bad requests it can. Also server responds, just the socket can’t receive data (checked in WireShark)
JavaScript
x
20
20
1
import socket
2
import ssl
3
4
HOST, PORT = 'example.com', 443
5
6
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
7
8
ssock = ssl.wrap_socket(sock)
9
ssock.connect((HOST, PORT))
10
11
raw_req = [f'GET / HTTP/1.1', 'Host: {HOST}', 'Connection: keep-alive']
12
req = 'n'.join(raw_req)
13
14
ssock.send(req.encode())
15
16
msg = ssock.recv(4096).decode()
17
print(msg)
18
19
ssock.close()
20
Advertisement
Answer
First, the HTTP GET expects a sequence of CR LF characters after each header line not just a single ‘n’ character and an extra CR LF after the last header line. Also, the join() adds the separator between each pair but not at the end so must append data with CR LF + CR LF to be a valid HTTP request.
Second, the 'Host: {HOST}'
must be a f-string otherwise the “{HOST}” is not replaced.
JavaScript
1
19
19
1
import socket
2
import ssl
3
4
HOST, PORT = 'stackoverflow.com', 443
5
6
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
7
ssock = ssl.wrap_socket(sock)
8
ssock.connect((HOST, PORT))
9
10
raw_req = [f'GET / HTTP/1.1', f'Host: {HOST}', 'Connection: keep-alive']
11
req = ('rn'.join(raw_req) + "rnrn").encode()
12
print("Request:", req)
13
14
ssock.send(req)
15
16
msg = ssock.recv(4096).decode()
17
print("nResponse:")
18
print(msg)
19
Output:
JavaScript
1
8
1
Request: b'GET / HTTP/1.1rnHost: stackoverflow.comrnConnection: keep-alivernrn'
2
3
Response:
4
HTTP/1.1 200 OK
5
Connection: keep-alive
6
content-type: text/html; charset=utf-8
7
8
If the HTTP response is larger than 4096 bytes then you would need to call ssock.recv()
in a loop until it returns a byte array of length 0.