1:在/etc/xinetd.d下添加配置文件xhttpd
service xhttpd
{
socket_type = stream //每行“=”前后各最多只能有一个空格
protocol= tcp
wait = no
user =nobody
server =/home/username/xhttpd/xhttpd //在xhttpd目录下有个xhttpd可执行文件
server_args = /home/username/dir //资源访问的目录
disable = no
flags = IPv4
}
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源码分析
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h> #define N 4096 void send_headers(char* type)
{
printf("HTTP/1.1 200 OK\r\n");
printf("Content-Type:%s; charset=utf-8\r\n",type);
printf("Connection:close\r\n");
printf("\r\n");
} void send_err()
{
//http protcol
//printf("HTTP/1.1 200 OK\r\n");
send_headers("text/html");
printf("<html>\r\n");
printf("<head><title>404 Can Not Find Page!</title></head>\r\n");
printf("<body>\r\n");
printf("Cann't Find Page!!!!\r\n");
printf("</body>\r\n");
printf("</html>\r\n");
exit();
} int main(int argc, char *argv[])
{
char line[N];
char method[N],path[N],protocol[N]; char *file;
struct stat sbuf;
FILE *fp;
int ich; // send_err();
// return 0; if(argc != )
{
send_err();
} if(chdir(argv[]) == -)
{
send_err();
} if(fgets(line,N,stdin) == NULL)
{
send_err();
} char headerInfo[];
strcpy(headerInfo,line); if(sscanf(line,"%[^ ] %[^ ] %[^ ]",method,path,protocol) != )
{
send_err(); //GET /hello.c HTTP/1.1
} while(fgets(line, N, stdin) != NULL)
if(strcmp(line,"\r\n"))
break; if(strcmp(method,"GET") != )
send_err(); if(path[] != '/')
send_err(); file = path+; if(stat(file,&sbuf) < )
send_err(); fp = fopen(file, "r");
if(fp == NULL)
send_err(); send_headers("text/plain");
//send_headers("audio/mpeg"); printf("method:%s\n",method);
printf("path:%s\n",path);
printf("protocol:%s\n",protocol);
printf("argv[0]:%s\n",argv[]);
printf("argv[1]:%s\n",argv[]);
printf("headerInfo:%s\n",headerInfo); while((ich = getc(fp)) != EOF)
putchar(ich); fflush(stdout);
fclose(fp);
return ;
}