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\r\n"); 12 printf("Content-Type:%s; charset=utf-8\r\n",type); 13 printf("Connection:close\r\n"); 14 printf("\r\n"); 15 } 16 17 void send_err() 18 { 19 //http protcol 20 //printf("HTTP/1.1 200 OK\r\n"); 21 send_headers("text/html"); 22 printf("<html>\r\n"); 23 printf("<head><title>404 Can Not Find Page!</title></head>\r\n"); 24 printf("<body>\r\n"); 25 printf("Cann't Find Page!!!!\r\n"); 26 printf("</body>\r\n"); 27 printf("</html>\r\n"); 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,"\r\n")) 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\n",method); 91 printf("path:%s\n",path); 92 printf("protocol:%s\n",protocol); 93 printf("argv[0]:%s\n",argv[0]); 94 printf("argv[1]:%s\n",argv[1]); 95 printf("headerInfo:%s\n",headerInfo); 96 97 while((ich = getc(fp)) != EOF) 98 putchar(ich); 99 100 fflush(stdout); 101 fclose(fp); 102 return 0; 103 }
作者:长风
Email:844064492@qq.com
QQ群:607717453
Git:https://github.com/zhaohu19910409Dz
开源项目:https://github.com/OriginMEK/MEK
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。
如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步