1:在/etc/xinetd.d下添加配置文件xhttpd
1 service xhttpd 2 { 3 socket_type = stream //每行“=”前后各最多只能有一个空格 4 protocol= tcp 5 wait = no 6 user =nobody 7 server =/home/username/xhttpd/xhttpd //在xhttpd目录下有个xhttpd可执行文件 8 server_args = /home/username/dir //资源访问的目录 9 disable = no 10 flags = IPv4 11 }
2:添加监听端口
vim /etc/service
添加两行:
xhttpd 10086/tcp
xhttpd 10086/udp
3:重启xinetd服务
sudo service xinetd restart
4:在浏览器中输入访问地址:127.0.0.1:10086/hello.txt
- 然后xinetd会启动xhttpd程序,并且传入两个默认参数:
- argv[0] = xhttpd
- argv[1] = /home/username/dir
- 分析http头信息
- GET /hello.txt HTTP/1.1
5:xhttpd.c源码分析
1 #include <stdlib.h> 2 #include <unistd.h> 3 #include <sys/stat.h> 4 #include <sys/types.h> 5 #include <stdio.h> 6 7 #define N 4096 8 9 void send_headers(char* type) 10 { 11 printf("HTTP/1.1 200 OK "); 12 printf("Content-Type:%s; charset=utf-8 ",type); 13 printf("Connection:close "); 14 printf(" "); 15 } 16 17 void send_err() 18 { 19 //http protcol 20 //printf("HTTP/1.1 200 OK "); 21 send_headers("text/html"); 22 printf("<html> "); 23 printf("<head><title>404 Can Not Find Page!</title></head> "); 24 printf("<body> "); 25 printf("Cann't Find Page!!!! "); 26 printf("</body> "); 27 printf("</html> "); 28 exit(0); 29 } 30 31 int main(int argc, char *argv[]) 32 { 33 char line[N]; 34 char method[N],path[N],protocol[N]; 35 36 char *file; 37 struct stat sbuf; 38 FILE *fp; 39 int ich; 40 41 // send_err(); 42 // return 0; 43 44 if(argc != 2) 45 { 46 send_err(); 47 } 48 49 if(chdir(argv[1]) == -1) 50 { 51 send_err(); 52 } 53 54 if(fgets(line,N,stdin) == NULL) 55 { 56 send_err(); 57 } 58 59 char headerInfo[256]; 60 strcpy(headerInfo,line); 61 62 if(sscanf(line,"%[^ ] %[^ ] %[^ ]",method,path,protocol) != 3) 63 { 64 send_err(); //GET /hello.c HTTP/1.1 65 } 66 67 68 while(fgets(line, N, stdin) != NULL) 69 if(strcmp(line," ")) 70 break; 71 72 if(strcmp(method,"GET") != 0) 73 send_err(); 74 75 if(path[0] != '/') 76 send_err(); 77 78 file = path+1; 79 80 if(stat(file,&sbuf) < 0) 81 send_err(); 82 83 fp = fopen(file, "r"); 84 if(fp == NULL) 85 send_err(); 86 87 send_headers("text/plain"); 88 //send_headers("audio/mpeg"); 89 90 printf("method:%s ",method); 91 printf("path:%s ",path); 92 printf("protocol:%s ",protocol); 93 printf("argv[0]:%s ",argv[0]); 94 printf("argv[1]:%s ",argv[1]); 95 printf("headerInfo:%s ",headerInfo); 96 97 while((ich = getc(fp)) != EOF) 98 putchar(ich); 99 100 fflush(stdout); 101 fclose(fp); 102 return 0; 103 }