0

I'm sending and get request to a server and receiving the response back, problem is, I just need to grab the headers to check the status code but the recv function seems to be stuck in the previous response, so even though I've sent a new request, I still keep receiving the first response. Now, how do I reset the recv function and grab only the headers, dropping everything else?

#define BUF_LEN 100
bytes_received = 1;
while(bytes_received = recv(sock, &get_response_buffer, BUF_LEN, 0) > 1)
{
    printf("\n----------RESPONSE-----------\n%s\n-----------------------------\n",get_response_buffer);
    // bytes_received = write(sock, &get_response_buffer, BUF_LEN);
    if(strstr(get_response_buffer, "HTTP/1.1 404 Not Found"))
    {
        printf("[404 NOT FOUND]\tGET %s%s\n",inet_ntoa(server_addr.sin_addr), read_string);
        break;
    }
    else if(strstr(get_response_buffer, "HTTP/1.1 302 Found"))
    {
        printf("[302 FOUND]\tGET %s%s\n", inet_ntoa(server_addr.sin_addr), read_string);
        break;
    }
    else if(strstr(get_response_buffer, "HTTP/1.1 200 OK"))
    {
        printf("[200 OK]\t GET %s%s\n", inet_ntoa(server_addr.sin_addr), read_string );
        break;
    }
    else
    {
        puts("not OK");
        break;
    }
}

Like so, both responses are from the first get request. If I keep sending more requests I just keep receiving the rest of the first request. ----------RESPONSE----------- HTTP/1.1 404 Not Found Cache-Control: public, max-age=1 Content-Type: text/html; charset=utf-8 Ex -----------------------------
----------RESPONSE----------- pires: Thu, 19 Oct 2017 14:37:14 GMT Last-Modified: Thu, 19 Oct 2017 14:37:13 GMT Vary: * X-AspNe -----------------------------

  • 2
    Note: you're not checking `recv`'s return (if there's an error, probably the buffer isn't modified). Also (for blocking sockets) the program execution would block if there is no data available. You could use `select` or `poll`. As an answer to your question __you can't__. `recv` (and sockets) work with data (which is a stream of bytes), they have absolutely no knowledge of the data _semantics_. So, you'll have to study the _HTTP_ protocol and do the parsing yourself (or use an existing library that does that). – CristiFati Oct 19 '17 at 14:44
  • You asked for 100 bytes in the `BUF_LEN` parameter. I didn't count, but each chunk you posted looks ~100 bytes. You have to read the *whole* HTTP message, and then throw away what you don't want. By the way, if you're not super comfortable with `recv(2)` and other networking concepts, you probably should not be writing your own HTTP parser in C. I'd recommend any one of the many libraries out there. – bnaecker Oct 19 '17 at 15:06
  • Also, `recv()` doesn't treat data as a C-style string. If one `recv()` gets 20 bytes and the next one 10, the old 11-20th bytes will still be in the buffer. – Andrew Henle Oct 19 '17 at 16:38

0 Answers0