Search code examples
pythonsocketshttpwebsockethttpserver

getting part of the recv() buffer


I have this code, that print the http server response, but now I'm trying to get the only the status code, and from there make decisions. like :

Code:200 - print ok code:404 - print page not found etc

PS: cant use http library

from socket import * 

#constants variables
target_host = 'localhost'
target_port = 80
target_dir = 'dashboard/index.html'

# create a socket object 
client = socket(AF_INET, SOCK_STREAM)  # create an INET (IPv4), STREAMing socket (TCP)
 
# connect the client 
client.connect((target_host,target_port))  
 
# send some data 
request = "GET /%s HTTP/1.1\r\nHost:%s\r\n\r\n" % (target_dir, target_host)

#Send data to the socket.
client.send(request.encode())  

# receive some data 
data = b''
while True: #while data
    buffer = client.recv(2048) #recieve a 2048 bytes data from socket
    if not buffer: #no more data, break
        break
    data += buffer #concatenate buffer data

client.close() #close buffer

#display the response
print(data.decode())

Solution

  • I would change the reception loop as below: extract the first line, split it, interpret the second word as an integer.

    line = b''
    while True:
        c = client.recv(1)
        if not c or c=='\n':
            break
        line += c
    
    status = -1
    line = line.split()
    if len(line)>=2:
      try:
        status = int(line[1])
      except:
        pass
    print(status)
    

    If we heavily rely on try we can simplify the second part

    try:
      status = int(line.split()[1])
    except:
      status = -1
    print(status)