Question

for some reason my headers are not being generated properly.

I'm sending a connected socket, along with a filename and response code 200. However, the method does not return anything.

Why?

void generate_header(int sock, char* filename, int response_code) {
  int i = 0;
  char buffer[BUFLEN];

  if (response_code == 200) {
    strncpy(buffer, "HTTP/1.1 200 OK\n", sizeof(buffer));
  } else if (response_code == 404) {

  } else if (response_code == 400) {

  } else {

  }

  strncpy(buffer, "Content-Type: text/html\n", sizeof(buffer) - strlen(buffer) - 1);
  strncpy(buffer, "Connection: close\n", sizeof(buffer) - strlen(buffer) - 1);
  strncpy(buffer, "\n", sizeof(buffer) - strlen(buffer) - 1);

  write(sock, buffer, strlen(buffer));


}
Was it helpful?

Solution

Simple: strncpy overwrites everything that your buffer held before.

The last strncpy just puts a newline character in, so that's all that will be printed.

Clear the buffer first, and use strncat instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top