编写简单http服务器(C语言)
2019-03-22 本文已影响0人
奋斗live
环境 : 腾讯云 centos7.2
以下是写的简单http服务器
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int server_sockfd;
int client_sockfd;
int len,pid;
struct sockaddr_in server_addr;
struct sockaddr_in remote_addr;
int sin_size;
char buf[BUFSIZ];
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
//用8000端口进行监听(注意开启服务器的防火墙,若是腾讯云或阿里云,注意加入安全组)
server_addr.sin_port = htons(8000);
if((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket failed\n");
exit(0);
}
if (bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0)
{
printf("bind failed\n");
exit(0);
}
listen(server_sockfd, 5);
sin_size = sizeof(struct sockaddr_in);
for(;;)
{
client_sockfd = accept(server_sockfd, (struct sockaddr *) &remote_addr, &sin_size);
if (client_sockfd < 0)
error("failed on accept");
//创建子进程
pid = fork();
if (pid < 0){
error("failed on fork");
}
if (pid == 0)//子进程
{
//由子进程为到来的连接提供服务
close(server_sockfd);
// 头部
char header[] = "HTTP/1.0 200 OK\r\n\r\n";
char html[] = "<!DOCTYPE html><html><head></head><body><h1>This is server_</h1></body></html>";
recv(client_sockfd, buf, BUFSIZ, 0);
printf("%s\n", buf);
send(client_sockfd,header,strlen(header),0);
send(client_sockfd, html, strlen(html), 0);
close(client_sockfd);//这里可关可不关,因为下面的exit退出自然会关掉连接套接字
exit(0);
}
close(client_sockfd);//父进程中一定要关闭连接套接字
}
close(server_sockfd);
return 0;
}
浏览器如下
image.png
服务器输出如下
image.png