1 Star 0 Fork 0

liweimin/c语言极简http-server

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.c 2.58 KB
一键复制 编辑 原始数据 按行查看 历史
liweimin 提交于 11个月前 . update main.c.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_BUF_SIZE 4096
#define RESPONSE_TEMPLATE "HTTP/1.1 200 OK\r\nServer: CMini\r\nContent-Type: text/html;charset=utf-8\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept\r\nContent-Length: %d\r\n\r\n%s"
void handle_client_request(int clifd) {
char buf[MAX_BUF_SIZE] = {};
while (read(clifd, buf, sizeof(buf)) > 0) {
if (strstr(buf, "exit")) {
close(clifd);
return;
} else if (strstr(buf, "ping")) {
FILE *fp = popen("ping www.baidu.com", "r");
if (fp) {
char bufp[MAX_BUF_SIZE];
fread(bufp, 1, sizeof(bufp) - 1, fp);
pclose(fp);
char response[MAX_BUF_SIZE];
sprintf(response, RESPONSE_TEMPLATE, strlen(bufp), bufp);
write(clifd, response, strlen(response) + 1);
}
} else {
char *result = "success";
char response[MAX_BUF_SIZE];
sprintf(response, RESPONSE_TEMPLATE, strlen(result), result);
write(clifd, response, strlen(response) + 1);
}
}
}
int main(int argc, char *argv[]) {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
return -1;
}
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(7777);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len = sizeof(addr);
if (bind(sockfd, (struct sockaddr*)&addr, len) < 0) {
perror("bind failed");
return -1;
}
if (listen(sockfd, 5) < 0) {
perror("listen failed");
return -1;
}
for (;;) {
struct sockaddr_in addrcli = {};
socklen_t lencli = sizeof(addrcli);
int clifd = accept(sockfd, (struct sockaddr*)&addrcli, &lencli);
if (clifd < 0) {
perror("accept failed");
continue;
}
if (fork() == 0) {
close(sockfd); // Child process doesn't need the listening socket
handle_client_request(clifd);
close(clifd); // Close client socket in child process
return 0; // Exit child process after handling request
}
close(clifd); // Parent process should close client socket
}
close(sockfd);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/gitlwm/c-simple-http-server.git
git@gitee.com:gitlwm/c-simple-http-server.git
gitlwm
c-simple-http-server
c语言极简http-server
master

搜索帮助