Eli R Eli R - 26 days ago 4
HTTP Question

Python TCP client not working

I'm having some issues with this python client. I'd appreciate it if someone could tell me what's wrong.

import socket, sys, time, os

host = '155.94.243.10'
port = 80

mySocket = socket.socket()
mySocket.connect((host,port))

message = input('>>>')
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print('Received from server: ' + str(data))
message = input('>>>')
mySocket.close()


I'm using "GET / HTTP/1.1" as the input.

I get no response from the server, I should be getting an error message (I think)

Edit: I used wireshark to confirm I am connecting to the server.

Thanks in advance.

Answer

Client has to send empty line aftera all headers. It inform server that it get all headers and it can send response (or it has to read body if you send POST).

import socket
import sys
import time
import os

#host = '155.94.243.10'
host = 'stackoverflow.com'
port = 80

mySocket = socket.socket()
mySocket.connect((host,port))

message = input('>>>')

while message != 'q':

    message += '\n\n'
    #message = 'GET / HTTP/1.1\n\n'

    mySocket.send(message.encode())
    data = mySocket.recv(1024).decode()
    print('Received from server: ' + str(data))
    message = input('>>>')
mySocket.close()

EDIT: It seems '155.94.243.10' needs other headers to get result. Try

message = 'GET / HTTP/1.1\nHost: 155.94.243.10\n\n'