Error: Expected: HTTP-version, Received: "" in C

I am stuck on Read request body #qv8 challenge, where I am reading the body and inserting it into a file. Everything seems to be working fine, but when I run the tests, I keep getting:

Error: Expected: HTTP-version, Received: ""

This is the code I have:

...
while (1){
		printf("Waiting for a client to connect...\n");
		client_addr_len = sizeof(client_addr);

		if((new_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_len)) == -1) {
			printf("Accept failed: %s \n", strerror(errno));
			close(server_fd);
			return 1;
		}
		printf("Client connected\n");

		int *new_fd_sock = malloc(sizeof(int));
		if (new_fd_sock == NULL) {
			fprintf(stderr, "error using malloc");
			continue;
		}

		*new_fd_sock = new_fd;
		
		pthread_t th;
		pthread_create(&th, NULL, *handle_request, new_fd_sock);
		pthread_detach(th);
	}

And the handle_request:

void *handle_request(void *arg) {
	int new_fd = *((int *)arg);

	free(arg);
	char request[512];
	recv(new_fd, request, sizeof request, 0);
	printf("%s\n\n", request);

	char msg[1000];
	...
	} else if(strcmp(path_first_param, "files") == 0) {
		char *file_name = strtok(NULL, "/");
		char file_path[100];
		strcpy(file_path, FILE_DIR);
		strcat(file_path, file_name);

		if(strcmp(method, "GET") == 0) {
			...
		} else if(strcmp(method, "POST") == 0) {
			char *body = strtok(request, "\n");
			for(i = 0; i < 7; i++)
				body = strtok(NULL, "\n");
			

			FILE* file = fopen(file_path, "w");
			if(file == NULL) {
				strcpy(msg, "HTTP/1.1 404 Not Found\r\n\r\n");
			} else {
				fprintf(file, "%s", body);

				snprintf(msg, 1000, "HTTP/1.1 201 Created\r\nContent-Type: application/octet-stream\r\nContent-Length: %zu\r\n\r\n%s", strlen(body), body);
			}
			fclose(file);
		}
	} else {
		strcpy(msg, "HTTP/1.1 404 Not Found\r\n\r\n");
	}

	printf("%s", msg);

	send(new_fd, msg, strlen(msg), 0);
	close(new_fd);

	return NULL;
}

Hey @Hazeman99, looks like you’ve got past this stage. Do you happen to remember what was wrong? Would love to see if we can improve the tester / instructions.

There are two things that I did that made it work.

The first thing was that I closed the file (fclose) only when the fopen returned a valid response and not NULL.

The second thing, which I still need to understand better, is that I assigned all functions that return values (not void) to variables (e.g. int val = fprintf(...)).

The testing results made me confused because I would get that same response but on different requests. Sometimes I would getit on GET /files/... and other times on POST /files/....

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.