Web服务器——C语言实现

    科技2024-12-20  7

    #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<assert.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<fcntl.h> #include<sys/stat.h> #define DATALENGTH 1024 #define PATHLENGTH 128 //发送HTTP应答报头 void SendHeadData(int c,int size,int flag) { char buff[DATALENGTH]="http/1.0"; if(flag) { strcat(buff,"200 OK\r\n"); } else { strcat(buff,"404 Not Found\r\n"); } strcat(buff,"Server:MyWeb/1.0\r\n"); strcat(buff,"Content-Length:"); sprintf(buff+strlen(buff),"%d",size); strcat(buff,"\r\n"); strcat(buff,"Content-Type:text/html;charset=utf-8\r\n"); strcat(buff,"\r\n"); send(c,buff,strlen(buff),0); } //发送页面内容 void SendFileData(int c,int fd) { while(1) { char buff[DATALENGTH]={0}; ssize_t n=read(fd,buff,DATALENGTH-1);//unsigned int 表示数据块的大小 if(n<=0) { break; } send(c,buff,(size_t)n,0); } } //处理客户端的请求数据 void DealClientData(int c) { char Rbuff[DATALENGTH]={0}; int n=recv(c,Rbuff,DATALENGTH-1,0); if(n<=0) { return; } char *file=strtok(Rbuff,"");//切割字符串,按“ ”将Rbuff切分成一个个子串.第一次被调用的时间str是传入需要被切割字符串的首地址;在后面调用的时间传入NULL。 file=strtok(NULL,"");//? int flag=1; char path[PATHLENGTH]="."; strcat(path,file); int fd=open(path,O_RDONLY); if(fd==-1) { fd=open("./404.html",O_RDONLY); flag=0; } struct stat st;//这个结构体是用来描述一个linux系统文件系统中的文件属性的结构。 fstat(fd,&st);通过文件描述符获取文件对应的属性。 SendHeadData(c,st.st_size,flag);//st.st_size文件字节数 SendFileData(c,fd); close(fd); } int InitSocket() { int sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd==-1)return -1; struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family=AF_INET; saddr.sin_port=htons(80); saddr.sin_addr.s_addr=inet_addr("192.168.43.239"); int res=bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); if(res==-1) { printf("bind errno\n"); return -1; } res=listen(sockfd,5); if(res==-1) { printf("listen errno\n"); return -1; } return sockfd; } int main() { int sockfd=InitSocket(); assert(sockfd!=-1); while(1) { struct sockaddr_in caddr; socklen_t len=sizeof(caddr); int c=accept(sockfd,(struct sockaddr*)&caddr,&len); if(c<0) { continue; } DealClientData(c); close(c); } exit(0); }
    Processed: 0.026, SQL: 8