请用C语言实现一个http服务器
时间: 2023-09-29 17:07:32 浏览: 85
基于C语言 HTTP 服务器客户端的实验【100010460】
5星 · 资源好评率100%
实现一个http服务器需要涉及到socket编程、HTTP协议的解析和文件读写等技术。下面是一个简单的使用C语言实现的http服务器的代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFSIZE 8096
void error(char *msg) {
perror(msg);
exit(1);
}
int main(int argc, char *argv[]) {
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
char buffer[BUFSIZE];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof(cli_addr);
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork();
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(sockfd);
memset(buffer, 0, BUFSIZE);
n = read(newsockfd, buffer, BUFSIZE - 1);
if (n < 0)
error("ERROR reading from socket");
if (strncmp(buffer, "GET /", 5) != 0) {
write(newsockfd, "HTTP/1.0 400 Bad Request\n", 25);
} else {
char *filename = buffer + 5;
char *end = strchr(filename, ' ');
if (end != NULL)
*end = '\0';
if (strlen(filename) == 0)
filename = "index.html";
FILE *file = fopen(filename, "r");
if (file == NULL) {
write(newsockfd, "HTTP/1.0 404 Not Found\n", 23);
} else {
write(newsockfd, "HTTP/1.0 200 OK\n", 16);
write(newsockfd, "Content-Type: text/html\n", 25);
write(newsockfd, "\n", 1);
while ((n = fread(buffer, 1, BUFSIZE, file)) > 0) {
write(newsockfd, buffer, n);
}
fclose(file);
}
}
close(newsockfd);
exit(0);
} else {
close(newsockfd);
}
}
close(sockfd);
return 0;
}
```
这段代码实现了一个简单的http服务器,只支持GET请求,只能读取当前目录下的html文件。在终端输入 `./http_server 8080` 即可启动服务器,其中8080是端口号,可以根据需要进行修改。
阅读全文