📄 webserver.c.bak
字号:
/*
the sample web server -----based in the HTTP
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <socklib.c>
#define BUFFSIZE 1024
#define oops(msg) {perror(msg);exit(1);}
main(int arvc,char *argv[])
{
int sock,fd;
FILE *fpin;
char request[BUFFSIZE];
if(argc == 1){
fprintf(stderr,"usage : ws portnum \n");
exit(1)
}
sock = make_server_socket(atoi(argv[1]));
if(sock == -1)
oops("build the socket")
while(1){
/*take a call and buffer it*/
fd=accept(sock,NULL,NULL);
fpin=fdopen(fd,"r");
/*read request*/
fgets(request,BUFFSIZE,fpin);
printf("got a call : request = %s",request);
read_til_crnl(fpin);
/*do what client asks*/
process_rq(request,fd);
fclose(fpin);
}
}
/*------------------------------------------------------------
read_til_crnl(FILE *)
--------------------------------------------------------------*/
read_til_crnl(FILE *fp)
{
char buf[BUFFSIZE];
while(fgets(buf,BUFFSIZE,fp) != NULL && strcmp(buf,"\r\n")!=0);
}
/*------------------------------------------------------------
process_rq(char *rq,int fd)
do what the request asks for and write reply to fd
handles request in a new process
rq is HTTP command : GET /foo/bar.html HTTP/1.0
----------------------------------------------------------------*/
process_rq(char *rq, int fd)
{
char cmd[BUFFSIZE] ,arg[BUFFSIZE];
/*creat a new process and return if not the child*/
if(fork()!=0)
return;
strcpy(arg,"./"); /*precede args with ./*/
if(sscanf(rq,"%s%s",cmd,arg+2)!=2)
return;
if(strcmp(cmd,"GET")!=0)
cannot_do(fd);
else if(not_exist(arg))
do_404(arg,fd);
else if(isadir(arg))
do_ls(arg,fd);
else if(ends_in_cgi(arg))
do_exec(arg,fd);
else
do_cat(arg,fd);
}
/*----------------------------------------------------------------------
the reply header thing:all functions need one
if content_type is NULL then don't send content type
------------------------------------------------------------------------*/
header(FILE *fp , char *content_type)
{
fprintf(fp,"HTTP/1.0 200 OK\r\n");
if(content_type)
fprintf(fp,"Content-type: %s\r\n",content_type);
}
/*---------------------------------------------------------------------
simple function first:
cannot_do(fd) unimplemented HTTP command
and do_404(item,fd) no such object
-----------------------------------------------------------------------*/
cannot_do(int fd)
{
FILE *fp = fdopen(fd,"w");
fprintf(fp,"HTTP/1.0 501 Not Implemented\r\n");
fprintf(fd,"Content-type:text/plain\r\n");
fprintf(fd,"\r\n");
fprintf(fd,"That command is not yet implemented\r\n");
fclose(fp);
}
do_404(char *item ,int fd)
{
FILE *fp = fdopen(fd,"w");
fprintf(fp,"HTTP/1.0 404 Not Found\r\n");
fprintf(fp,"Content-type:t
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -