我正在尝试使用 C 中的套接字编写一个基本的 HTTP 文件服务器,但有两个主要问题。
首先,当我尝试通过浏览器访问“ip:port/”时,我得到了 index.html 文件,但它完全是乱码。但是,当我访问“ip:port/not_in_directory”时,我的小自定义 404 消息会正常返回。如果我将默认文件设置为现有的 pdf 文件,乱码也会回来(pdf 乱码的长度)。
其次,当我尝试访问“ip:port/file_that_exists”时,我得到的是 404 而不是正确的文件。在调试时,我确实看到 scratch_pad 具有正确的文件名,没有多余或丢失的字符,但是 !access(scratch_pad, R_OK) 仍然为 0。即使 access() 需要一个 char* 是否也有一些必要的转换为文件名?
编辑:第二个问题已解决(我使用指向已释放缓冲区的指针作为文件名)。但是,浏览器获取的所有内容都是胡言乱语。我正在删除更多非必要的代码。
#define FILE_NOT_FOUND "HTTP/1.0 404 FILE NOT FOUND\r\n"
#define FILE_FOUND "HTTP/1.0 200 OK\r\n"
#define SERVER_NAME "Server: Test Server\r\n"
#define CONTENT_TYPE "Content-Type: text/html\r\n"
#define DATE "Date: "
#define MESSAGE_BREAK "\r\n"
#define NOT_FOUND_HTML "<!DOCTYPE html>\n<html>\n<title>404 Not Found</title>\n<body>\n<p>Nope</p>\n</body>\n</html>\r\n"
if(!access(pulled_name, R_OK | W_OK)) {
printf("file found on server\n");
server_file = fopen(pulled_name, "rb+");
fseek(server_file, 0L, SEEK_END);
file_size = ftell(server_file);
fseek(server_file, 0l, SEEK_SET);
printf("opened successfully and set file_size to %i\n", file_size);
getting_time = time(NULL);
c_time = localtime(&getting_time);
current_time = asctime(c_time);
printf("set time for message\n");
message = malloc((int) strlen(FILE_FOUND)
+ (int) strlen(SERVER_NAME)
+ (int) strlen(CONTENT_TYPE)
+ (int) strlen(DATE)
+ (int) strlen(current_time)
+ (int) strlen(MESSAGE_BREAK));
printf("malloc'ed message\n");
message_size = (int)(strlen(message)*sizeof(char));
memset(message, 0, message_size);
strcpy(message, FILE_FOUND);
strcat(message, SERVER_NAME);
strcat(message, CONTENT_TYPE);
strcat(message, DATE);
strcat(message, current_time);
strcat(message, MESSAGE_BREAK);
printf("built message\n");
printf("set message_size to %i\n", message_size);
while(total_sent < message_size) {
n = send(new_socket_fd, message, message_size, 0);
if (n==-1) {
printf("error sending message\n");
break;
}
total_sent += n;
printf("sent %i\n", total_sent);
}
free(message);
total_sent = 0;
while(total_sent < file_size) {
n = send(new_socket_fd, server_file, file_size, 0);
if (n==-1) {
printf("error sending file\n");
break;
}
total_sent += n;
printf("sent %i\n", total_sent);
}
fclose(server_file);
close(new_socket_fd);
printf("closed client connection!\n");