chttpserverhttp-headers

Handling HTTP Headers in a Minimal C HTTP Server


I’m working on a minimal HTTP server in C that can listen, bind, accept connections, and handle basic HTTP requests. I understand that HTTP headers are important for communicating additional information between the client and server, but I’m unsure how to properly handle and respond to them.

Here’s a snippet of my code:

void HandleHeaders(int ClientSocket, char *request){
  
  char response[BUFFER_SIZE];
}

void HandleResponse(int ClientSocket, char *request){
  char *response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHOLA\n";
  write(ClientSocket, response, strlen(response));
}

void HandleRequest(int ServerSocket, int ClientSocket){
    //Obtener los datos recibidos del socket y los almacena en un buffer
    char request [BUFFER_SIZE]; //Buffer
    
    int DatosDelBuffer = recv(ClientSocket, request, sizeof(request), 0);

    //Verificamos el contenido del buffer
    if(DatosDelBuffer < 0 ){
      perror("Error leer el buffer!\n");
      exit(EXIT_FAILURE);
    } else if(strncmp(request,"GET / ",6) == 0){
      printf("%s\n",request); 
      HandleResponse(ClientSocket,request);
    } else if(strncmp(request, "GET /headers",12) == 0){
      HandleHeaders(ClientSocket, request);
    } else {
      char *response = "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\n404 Not Found";
      write(ClientSocket, response, strlen(response)); 
    }    
    
    //Cierra el Socket y termina la conexion
    close(ClientSocket);
}
  

I’ve tried looking online for examples or explanations, but most results just define HTTP headers without showing how to process them in C.

Questions:

I appreciate any help or examples!


Solution

  • First of all, don't confuse an HTTP HEAD request method with HTTP request and response headers—these are separate concepts.

    To properly handle HTTP headers in your server, refer to the HTTP specifications, which define how your server should react to different request headers. For example:

    1. General HTTP Headers

    2. Caching & Conditional Requests

    3. Security & Authentication

    4. Content Negotiation

    5. Client & Server Communication

    6. Miscellaneous

    To implement everything correctly, you will need to consult a multitude of RFCs and check the easily underestimated complexity of open source projects like C-Web-Server or Apache ;-).