#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
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);
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,"");
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;
fstat(fd,&st);
SendHeadData(c,st.st_size,flag);
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);
}
转载请注明原文地址:https://blackberry.8miu.com/read-35471.html