此源码基于C语言,500行代码实现http服务器通信,包含套接字,线程
初次阅读源码,请批评指正
github源码+简要解析
sourceforge源码(得到一个tar.gz文件,可在linux下直接解压)
本人linux虚拟机使用的是centos7,运行过程中遇到了一些问题
首先作者已经讲明在linux运行时需要对代码做一些更改
由于源码来源不同,源代码的makefile内容也有所不同,因此此处只展示最终修改的结果
具体修改如下
本人输入颜色后出现页面发生跳转但颜色未改变的情况
建议源码阅读顺序: main -> startup -> accept_request -> execute_cgi, 通晓主要工作流程后再仔细把每个函数的源码看一看。
/**********************************************************************/
/* This function starts the process of listening for web connections
* on a specified port. If the port is 0, then dynamically allocate a
* port and modify the original port variable to reflect the actual
* port.
* Parameters: pointer to variable containing the port to connect on 指针类型
* Returns: the socket */
// 初始化 httpd 服务,包括建立套接字,绑定端口,进行监听等。
/**********************************************************************/
int startup(u_short *port)
{
int httpd = 0;//表示一个套接字的描述符
int on = 1;//缓冲区
struct sockaddr_in name;// 在#include 中定义
//建立套接字
// socket(domain:通信域(unix,IPV4,IPV6), type:通信类型(面向连接、非面向连接), protocol:协议(TCP,UDP,0表示根绝前两个参数使用默认的协议))
httpd = socket(PF_INET, SOCK_STREAM, 0);
// 如果函数调用成功,会返回一个标识这个套接字的文件描述符,失败的时候返回-1
if (httpd == -1)
error_die("socket");// 把错误信息写到 perror 并退出。
memset(&name, 0, sizeof(name));
//访问name的成员变量,main函数中有定义
name.sin_family = AF_INET;
name.sin_port = htons(*port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
//设置建立socket
//setsocket(表示一个套接字的描述符, 选项定义的层次, 需设置的选项, 指向存放选项值的缓冲区指针, 缓冲区长度)
if ((setsockopt(httpd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0) // setsockopt()返回0。否则的话,返回-1错误
error_die("setsockopt failed");
//绑定socket
//int bind(int sockfd, const struct sockaddr *addr,socklen_t *addrlen);
//bind()把用addr指定的地址赋值给用文件描述符代表的套接字sockfd
//addrlen指定了以addr所指向的地址结构体的字节长度。一般来说,该操作称为“给套接字命名”。
//通常,在一个SOCK_STREAM套接字接收连接之前,必须通过bind()函数用本地地址为套接字命名。
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)// 成功,返回0;出错,返回-1
error_die("bind");
//如果端口没有设置,提供个随机端口
if (*port == 0) /* if dynamically allocating a port */
{
socklen_t namelen = sizeof(name);
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
error_die("getsockname");
//ntohs()将一个无符号短整型数从网络自结婚孙旭转换为主机字节顺序
*port = ntohs(name.sin_port);//修改port的值
}
//进行监听
//listen(一个已绑定未被连接的套接字描述符,连接请求队列的最大长度)
//队列满,将拒绝新的连接请求
if (listen(httpd, 5) < 0)//无错误返回0
error_die("listen");
return(httpd);
}
/**********************************************************************/
/* A request has caused a call to accept() on the server port to
* return. Process the request appropriately.
* Parameters: the socket connected to the client */
//处理从套接字上监听到的一个 HTTP 请求,在这里可以很大一部分地体现服务器处理请求流程
/**********************************************************************/
void accept_request(void *arg)
{
int client = (intptr_t)arg;
char buf[1024];
size_t numchars;
char method[255];//HTTP请求的method
char url[255];
char path[512];
size_t i, j;
struct stat st;// 获取文件信息
//struct stat{
// dev_t st_dev; /* ID of device containing file */文件使用的设备号
// ino_t st_ino; /* inode number */ 索引节点号
// mode_t st_mode; /* protection */ 文件对应的模式,文件,目录等
// nlink_t st_nlink; /* number of hard links */ 文件的硬连接数
// uid_t st_uid; /* user ID of owner */ 所有者用户识别号
// gid_t st_gid; /* group ID of owner */ 组识别号
// dev_t st_rdev; /* device ID (if special file) */ 设备文件的设备号
// off_t st_size; /* total size, in bytes */ 以字节为单位的文件容量
// blksize_t st_blksize; /* blocksize for file system I/O */ 包含该文件的磁盘块的大小
// blkcnt_t st_blocks; /* number of 512B blocks allocated */ 该文件所占的磁盘块
// time_t st_atime; /* time of last access */ 最后一次访问该文件的时间
// time_t st_mtime; /* time of last modification */ /最后一次修改该文件的时间
// time_t st_ctime; /* time of last status change */ 最后一次改变该文件状态的时间
//};
//标记是否是cgi程序
int cgi = 0; /* becomes true if server decides this is a CGI program */
char *query_string = NULL;
numchars = get_line(client, buf, sizeof(buf));//返回缓冲区最后一个字符下标
i = 0; j = 0;
//buf的内容: GET / HTTP/1.1
// GET / favicon.ico HTTP/1.1
// POST / color.cgi HTTP/1.1
//其中包含method,url
//获取buf中的method
//method的内容:GET
// GET
// POST
while (!ISspace(buf[i]) && (i < sizeof(method) - 1))//获取method
{
method[i] = buf[i];
i++;
}
j=i;
method[i] = '\0';
//strcasecmp()用忽略大小写比较字符串
//返回值 若参数s1和s2字符串相等则返回0。s1大于s2则返回大于0 的值,s1 小于s2 则返回小于0的值。
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))//比较失败,不为GET,POST
{
unimplemented(client);
return;
}
if (strcasecmp(method, "POST") == 0)//为POST请求
cgi = 1;//cgi置为1
i = 0;
//获取到buf中的url
//url的内容:/
// /favicon.ico
// /color.cgi
while (ISspace(buf[j]) && (j < numchars))//跳过空格
j++;
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
{
url[i] = buf[j];
i++; j++;
}
url[i] = '\0';
if (strcasecmp(method, "GET") == 0)//为GET请求
{
query_string = url;
while ((*query_string != '?') && (*query_string != '\0'))
query_string++;
if (*query_string == '?')//如果有携带参数,则 query_string 指针指向 url 中 ? 后面的 GET 参数。
{
cgi = 1;
*query_string = '\0';
query_string++;
}
}
//获取路径
sprintf(path, "htdocs%s", url);
//默认地址,解析到的路径如果为/,则自动加上index.html
if (path[strlen(path) - 1] == '/')
strcat(path, "index.html");
//定义函数:int stat(const char * file_name, struct stat *buf);
//函数说明:stat()用来将参数file_name 所指的文件状态, 复制到参数buf 所指的结构中。
//返回值:执行成功则返回0,失败返回-1,错误代码存于errno。
if (stat(path, &st) == -1) {
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
not_found(client);
}
else
{
if ((st.st_mode & S_IFMT) == S_IFDIR)//如果文件路径合法,对于无参数的 GET 请求,直接输出服务器文件到浏览器,即用 HTTP 格式写到套接字上
strcat(path, "/index.html");
if ((st.st_mode & S_IXUSR) ||
(st.st_mode & S_IXGRP) ||
(st.st_mode & S_IXOTH) )//其他情况(带参数 GET,POST 方式,url 为可执行文件),则调用 excute_cgi 函数执行 cgi 脚本。
cgi = 1;
if (!cgi)
serve_file(client, path);
else
execute_cgi(client, path, method, query_string);
}
close(client);
}
int get_line(int sock, char *buf, int size)
{
int i = 0;
char c = '\0';//TCP接收的数据
int n;
while ((i < size - 1) && (c != '\n'))// \n 换行(当前位置移到下一行)
{
//int recv(SOCKET s,char FAR *buf,int len,int flags);
//第一个参数:接收端的套接字描述符,其实就是客户端对应的套接字;第二个参数:指向接受的数据所在的缓冲区;第三个参数:缓冲区的最大尺寸,sizeof();第四个参数:置0就完事了
//如果recv函数成功,返回值大于0,返回的是其实际copy的字节数;
//如果recv在copy时出错,那么它返回SOCKET_ERROR;
//如果recv函数在等待协议接收数据时网络中断了,那么它返回0。
n = recv(sock, &c, 1, 0);//不论是客户还是服务器应用程序都用recv函数从TCP连接的另一端接收数据。
/* DEBUG printf("%02X\n", c); */
if (n > 0)
{
if (c == '\r')// \r 回车(当前位置移到本行开头)
{
n = recv(sock, &c, 1, MSG_PEEK);
/* DEBUG printf("%02X\n", c); */
if ((n > 0) && (c == '\n'))
recv(sock, &c, 1, 0);
else
c = '\n';
}
buf[i] = c;//把method数据存入buf
i++;
}
else
c = '\n';
}
buf[i] = '\0';
return(i);//返回缓冲区最后一个字符下标
}
/* J. David's webserver */ /* This is a simple webserver. * Created November 1999 by J. David Blackstone. * CSE 4344 (Network concepts), Prof. Zeigler * University of Texas at Arlington */ /* This program compiles for Sparc Solaris 2.6. * To compile for Linux: * 1) Comment out the #include
line. * 2) Comment out the line that defines the variable newthread. * 3) Comment out the two lines that run pthread_create(). * 4) Uncomment the line that runs accept_request(). * 5) Remove -lsocket from the Makefile. */ #include#include #include #include #include #include #include #include #include #include #include #include #include #include //如果 c 是一个空白字符,则该函数返回非零值(true),否则返回 0(false)。 // \t\n\v\f\r均为空白字符 #define ISspace(x) isspace((int)(x)) #define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n" #define STDIN 0 #define STDOUT 1 #define STDERR 2 void accept_request(void *); void bad_request(int); void cat(int, FILE *); void cannot_execute(int); void error_die(const char *); void execute_cgi(int, const char *, const char *, const char *); int get_line(int, char *, int); void headers(int, const char *); void not_found(int); void serve_file(int, const char *); int startup(u_short *); void unimplemented(int); /**********************************************************************/ /* A request has caused a call to accept() on the server port to * return. Process the request appropriately. * Parameters: the socket connected to the client */ //处理从套接字上监听到的一个 HTTP 请求,在这里可以很大一部分地体现服务器处理请求流程 /**********************************************************************/ void accept_request(void *arg) { int client = (intptr_t)arg; char buf[1024]; size_t numchars; char method[255];//HTTP请求的method char url[255]; char path[512]; size_t i, j; struct stat st;// 获取文件信息 //struct stat{ // dev_t st_dev; /* ID of device containing file */文件使用的设备号 // ino_t st_ino; /* inode number */ 索引节点号 // mode_t st_mode; /* protection */ 文件对应的模式,文件,目录等 // nlink_t st_nlink; /* number of hard links */ 文件的硬连接数 // uid_t st_uid; /* user ID of owner */ 所有者用户识别号 // gid_t st_gid; /* group ID of owner */ 组识别号 // dev_t st_rdev; /* device ID (if special file) */ 设备文件的设备号 // off_t st_size; /* total size, in bytes */ 以字节为单位的文件容量 // blksize_t st_blksize; /* blocksize for file system I/O */ 包含该文件的磁盘块的大小 // blkcnt_t st_blocks; /* number of 512B blocks allocated */ 该文件所占的磁盘块 // time_t st_atime; /* time of last access */ 最后一次访问该文件的时间 // time_t st_mtime; /* time of last modification */ /最后一次修改该文件的时间 // time_t st_ctime; /* time of last status change */ 最后一次改变该文件状态的时间 //}; //标记是否是cgi文件 int cgi = 0; /* becomes true if server decides this is a CGI program */ char *query_string = NULL; numchars = get_line(client, buf, sizeof(buf));//返回缓冲区最后一个字符下标 i = 0; j = 0; //buf的内容: GET / HTTP/1.1 // GET / favicon.ico HTTP/1.1 // POST / color.cgi HTTP/1.1 //其中包含method,url //获取buf中的method //method的内容:GET // GET // POST while (!ISspace(buf[i]) && (i < sizeof(method) - 1))//获取method { method[i] = buf[i]; i++; } j=i; method[i] = '\0'; //strcasecmp()用忽略大小写比较字符串 //返回值 若参数s1和s2字符串相等则返回0。s1大于s2则返回大于0 的值,s1 小于s2 则返回小于0的值。 if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))//比较失败,不为GET,POST { unimplemented(client); return; } if (strcasecmp(method, "POST") == 0)//为POST请求 cgi = 1;//cgi置为1 i = 0; //获取到buf中的url //url的内容:/ // /favicon.ico // /color.cgi while (ISspace(buf[j]) && (j < numchars))//跳过空格 j++; while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars)) { url[i] = buf[j]; i++; j++; } url[i] = '\0'; if (strcasecmp(method, "GET") == 0)//为GET请求 { query_string = url; while ((*query_string != '?') && (*query_string != '\0')) query_string++; if (*query_string == '?')//如果有携带参数,则 query_string 指针指向 url 中 ? 后面的 GET 参数。 { cgi = 1; *query_string = '\0'; query_string++; } } //获取路径 sprintf(path, "htdocs%s", url); //默认地址,解析到的路径如果为/,则自动加上index.html if (path[strlen(path) - 1] == '/') strcat(path, "index.html"); //定义函数:int stat(const char * file_name, struct stat *buf); //函数说明:stat()用来将参数file_name 所指的文件状态, 复制到参数buf 所指的结构中。 //返回值:执行成功则返回0,失败返回-1,错误代码存于errno。 if (stat(path, &st) == -1) { while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ numchars = get_line(client, buf, sizeof(buf)); not_found(client); } else { if ((st.st_mode & S_IFMT) == S_IFDIR)//如果文件路径合法,对于无参数的 GET 请求,直接输出服务器文件到浏览器,即用 HTTP 格式写到套接字上 strcat(path, "/index.html");//拼接路径 if ((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH) )//其他情况(带参数 GET,POST 方式,url 为可执行文件),则调用 excute_cgi 函数执行 cgi 脚本。 cgi = 1; if (!cgi)//cgi为0,说明不是cgi文件 serve_file(client, path); else//是cgi文件 execute_cgi(client, path, method, query_string);//运行cgi文件 } close(client); } /**********************************************************************/ /* Inform the client that a request it has made has a problem. * Parameters: client socket */ /**********************************************************************/ void bad_request(int client) { char buf[1024]; sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "Content-type: text/html\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, " Your browser sent a bad request, "); send(client, buf, sizeof(buf), 0); sprintf(buf, "such as a POST without a Content-Length.\r\n"); send(client, buf, sizeof(buf), 0); } /**********************************************************************/ /* Put the entire contents of a file out on a socket. This function * is named after the UNIX "cat" command, because it might have been * easier just to do something like pipe, fork, and exec("cat"). * Parameters: the client socket descriptor * FILE pointer for the file to cat */ //读取服务器上某个文件写到 socket 套接字。 /**********************************************************************/ void cat(int client, FILE *resource) { char buf[1024]; fgets(buf, sizeof(buf), resource);//从resource中读取sizeof(buf) - 1个字符存入buf //feof()是文件结束检测函数来,如果没有结束,返回值是0,结束百了是1 while (!feof(resource))//文件未结束 { send(client, buf, strlen(buf), 0);//send()向一个已经连接的socket,即client发送数据 fgets(buf, sizeof(buf), resource); } } /**********************************************************************/ /* Inform the client that a CGI script could not be executed. * Parameter: the client socket descriptor. */ //主要处理发生在执行 cgi 程序时出现的错误 /**********************************************************************/ void cannot_execute(int client) { char buf[1024]; sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "
Error prohibited CGI execution.\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ /* Print out an error message with perror() (for system errors; based * on value of errno, which indicates system call errors) and exit the * program indicating an error. */ // 把错误信息写到 perror 并退出。 /**********************************************************************/ void error_die(const char *sc) { perror(sc); exit(1); } /**********************************************************************/ /* Execute a CGI script. Will need to set environment variables as * appropriate. * Parameters: client socket descriptor * path to the CGI script */ //运行 cgi 程序的处理 /**********************************************************************/ void execute_cgi(int client, const char *path, const char *method, const char *query_string) { char buf[1024]; int cgi_output[2];//管道的两个文件描述符 int cgi_input[2]; pid_t pid;//进程唯一标识符,可在同一主机中标识唯一的进程 int status; int i; char c; int numchars = 1; int content_length = -1; buf[0] = 'A'; buf[1] = '\0'; if (strcasecmp(method, "GET") == 0)//是get请求 while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ numchars = get_line(client, buf, sizeof(buf)); else if (strcasecmp(method, "POST") == 0) /*是POST请求*/ { numchars = get_line(client, buf, sizeof(buf)); while ((numchars > 0) && strcmp("\n", buf))//找出 Content-Length { buf[15] = '\0'; if (strcasecmp(buf, "Content-Length:") == 0)//找到content-length content_length = atoi(&(buf[16]));//atoi()是把字符串转换成整型数的一个函数 numchars = get_line(client, buf, sizeof(buf)); } if (content_length == -1) {//未找到content-length bad_request(client); return; } } else/*HEAD or other*/ { } //int pipe(int fd[2]) 创建管道 //返回值:成功,返回0,否则返回-1。参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道 if (pipe(cgi_output) < 0) {//创建输出管道失败 cannot_execute(client); return; } if (pipe(cgi_input) < 0) {//创建输入管道失败 cannot_execute(client); return; } //fork() 函数调用一次,返回两次 //有三种不同的返回值:在父进程中,fork返回新创建子进程的进程ID;在子进程中,fork返回0;如果出现错误,fork返回一个负值 if ( (pid = fork()) < 0 ) {//fork()出现错误 cannot_execute(client); return; } sprintf(buf, "HTTP/1.0 200 OK\r\n");//把 HTTP 200 状态码写到套接字 send(client, buf, strlen(buf), 0); //父子线程同时运行,即if和else均会执行 if (pid == 0) /* 子线程child: CGI script */ { char meth_env[255]; char query_env[255]; char length_env[255]; dup2(cgi_output[1], STDOUT);//把 STDOUT 重定向到 cgi_output 的写入端,即cgi_output的写入端指向STDOUT dup2(cgi_input[0], STDIN);//把 STDIN 重定向到 cgi_input 的读取端 close(cgi_output[0]); close(cgi_input[1]);//关闭 cgi_input 的写入端 和 cgi_output 的读取端 sprintf(meth_env, "REQUEST_METHOD=%s", method);//设置 request_method 的环境变 putenv(meth_env);//putenv()用来改变或增加环境变量的内容 if (strcasecmp(method, "GET") == 0) {//get请求 sprintf(query_env, "QUERY_STRING=%s", query_string);//设置 query_string 的环境变量 putenv(query_env); } else { /* 父线程POST */ sprintf(length_env, "CONTENT_LENGTH=%d", content_length);//设置 content_length 的环境变量 putenv(length_env); } //int execl(const char * path, const char * arg, ...); //execl()用来执行参数path 字符串所代表的文件路径, 接下来的参数代表执行该文件时传递过去的argv(0), argv[1], ..., 最后一个参数必须用空指针(NULL)作结束. //如果执行成功则函数不会返回, 执行失败则直接返回-1, 失败原因存于errno 中. execl(path, NULL); exit(0); } else { /* parent */ close(cgi_output[1]);//关闭 cgi_input 的读取端 和 cgi_output 的写入端 close(cgi_input[0]); if (strcasecmp(method, "POST") == 0)//是post请求 { for (i = 0; i < content_length; i++) {//把 POST 数据写入 cgi_input,已被重定向到 STDIN recv(client, &c, 1, 0); write(cgi_input[1], &c, 1); } } //从output管道读到子进程处理后的信息,然后send出去 while (read(cgi_output[0], &c, 1) > 0) send(client, &c, 1, 0); close(cgi_output[0]);//关闭 cgi_input 的写入端 和 cgi_output 的读取端 close(cgi_input[1]); waitpid(pid, &status, 0);//waitpid()会暂时停止目前进程的执行, 直到有信号来到或子进程结束. } } /**********************************************************************/ /* Get a line from a socket, whether the line ends in a newline, * carriage return, or a CRLF combination. Terminates the string read * with a null character. If no newline indicator is found before the * end of the buffer, the string is terminated with a null. If any of * the above three line terminators is read, the last character of the * string will be a linefeed and the string will be terminated with a * null character. * Parameters: the socket descriptor 套接字描述符 * the buffer to save the data in 缓冲区 * the size of the buffer 缓冲区大小 * Returns: the number of bytes stored (excluding null) */ //读取套接字的一行,把回车换行等情况都统一为换行符结束。 /**********************************************************************/ int get_line(int sock, char *buf, int size) { int i = 0; char c = '\0';//TCP接收的数据 int n; while ((i < size - 1) && (c != '\n'))// \n 换行(当前位置移到下一行) { //int recv(SOCKET s,char FAR *buf,int len,int flags); //第一个参数:接收端的套接字描述符,其实就是客户端对应的套接字;第二个参数:指向接受的数据所在的缓冲区;第三个参数:缓冲区的最大尺寸,sizeof();第四个参数:置0就完事了 //如果recv函数成功,返回值大于0,返回的是其实际copy的字节数; //如果recv在copy时出错,那么它返回SOCKET_ERROR; //如果recv函数在等待协议接收数据时网络中断了,那么它返回0。 n = recv(sock, &c, 1, 0);//不论是客户还是服务器应用程序都用recv函数从TCP连接的另一端接收数据。 /* DEBUG printf("%02X\n", c); */ if (n > 0) { if (c == '\r')// \r 回车(当前位置移到本行开头) { n = recv(sock, &c, 1, MSG_PEEK); /* DEBUG printf("%02X\n", c); */ if ((n > 0) && (c == '\n')) recv(sock, &c, 1, 0); else c = '\n'; } buf[i] = c;//把method数据存入buf i++; } else c = '\n'; } buf[i] = '\0'; return(i);//返回缓冲区最后一个字符下标 } /**********************************************************************/ /* Return the informational HTTP headers about a file. */ /* Parameters: the socket to print the headers on * the name of the file */ //把 HTTP 响应的头部写到套接字 /**********************************************************************/ void headers(int client, const char *filename) { char buf[1024]; (void)filename; /* could use filename to determine file type */ strcpy(buf, "HTTP/1.0 200 OK\r\n"); send(client, buf, strlen(buf), 0);//send()向一个已经连接的socket发送数据 strcpy(buf, SERVER_STRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n"); send(client, buf, strlen(buf), 0); strcpy(buf, "\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ /* Give a client a 404 not found status message. */ //主要处理找不到请求的文件时的情况。 /**********************************************************************/ void not_found(int client) { char buf[1024]; sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, SERVER_STRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "
Not Found \r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "The server could not fulfill\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "your request because the resource specified\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "is unavailable or nonexistent.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ /* Send a regular file to the client. Use headers, and report * errors to client if they occur. * Parameters: a pointer to a file structure produced from the socket * file descriptor * the name of the file to serve */ //调用 cat 把服务器文件返回给浏览器,参数:客户端,文件路径 /**********************************************************************/ void serve_file(int client, const char *filename) { FILE *resource = NULL; int numchars = 1; char buf[1024]; buf[0] = 'A'; buf[1] = '\0'; while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ numchars = get_line(client, buf, sizeof(buf)); resource = fopen(filename, "r");//读文件 if (resource == NULL)//文件为空 not_found(client); else { headers(client, filename); cat(client, resource); } fclose(resource); } /**********************************************************************/ /* This function starts the process of listening for web connections * on a specified port. If the port is 0, then dynamically allocate a * port and modify the original port variable to reflect the actual * port. * Parameters: pointer to variable containing the port to connect on 指针类型 * Returns: the socket */ // 初始化 httpd 服务,包括建立套接字,绑定端口,进行监听等。 /**********************************************************************/ int startup(u_short *port) { int httpd = 0;//表示一个套接字的描述符 int on = 1;//缓冲区 struct sockaddr_in name;// 在#include
中定义 //建立套接字 // socket(domain:通信域(unix,IPV4,IPV6), type:通信类型(面向连接、非面向连接), protocol:协议(TCP,UDP,0表示根绝前两个参数使用默认的协议)) httpd = socket(PF_INET, SOCK_STREAM, 0); // 如果函数调用成功,会返回一个标识这个套接字的文件描述符,失败的时候返回-1 if (httpd == -1) error_die("socket");// 把错误信息写到 perror 并退出。 memset(&name, 0, sizeof(name)); //访问name的成员变量,main函数中有定义 name.sin_family = AF_INET; name.sin_port = htons(*port); name.sin_addr.s_addr = htonl(INADDR_ANY); //设置建立socket //setsocket(表示一个套接字的描述符, 选项定义的层次, 需设置的选项, 指向存放选项值的缓冲区指针, 缓冲区长度) if ((setsockopt(httpd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0) // setsockopt()返回0。否则的话,返回-1错误 error_die("setsockopt failed"); //绑定socket //int bind(int sockfd, const struct sockaddr *addr,socklen_t *addrlen); //bind()把用addr指定的地址赋值给用文件描述符代表的套接字sockfd //addrlen指定了以addr所指向的地址结构体的字节长度。一般来说,该操作称为“给套接字命名”。 //通常,在一个SOCK_STREAM套接字接收连接之前,必须通过bind()函数用本地地址为套接字命名。 if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)// 成功,返回0;出错,返回-1 error_die("bind"); //如果端口没有设置,提供个随机端口 if (*port == 0) /* if dynamically allocating a port */ { socklen_t namelen = sizeof(name); if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1) error_die("getsockname"); //ntohs()将一个无符号短整型数从网络自结婚孙旭转换为主机字节顺序 *port = ntohs(name.sin_port);//修改port的值 } //进行监听 //listen(一个已绑定未被连接的套接字描述符,连接请求队列的最大长度) //队列满,将拒绝新的连接请求 if (listen(httpd, 5) < 0)//无错误返回0 error_die("listen"); return(httpd); } /**********************************************************************/ /* Inform the client that the requested web method has not been * implemented. * Parameter: the client socket */ //返回给浏览器表明收到的 HTTP 请求所用的 method 不被支持。 /**********************************************************************/ void unimplemented(int client) { char buf[1024]; sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, SERVER_STRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Method Not Implemented\r\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">send</span><span class="token punctuation">(</span>client<span class="token punctuation">,</span> buf<span class="token punctuation">,</span> <span class="token function">strlen</span><span class="token punctuation">(</span>buf<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token function">sprintf</span><span class="token punctuation">(</span>buf<span class="token punctuation">,</span> <span class="token string">" \r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "
HTTP request method not supported.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ int main(void) { int server_sock = -1; u_short port = 4000;//端口号 int client_sock = -1; // 在#include
中定义 /*struct sockaddr_in{ short sin_family;// Address family一般来说AF_INET(地址族)PF_INET(协议族) unsigned short sin_port;// Port number(必须要采用网络数据格式,普通数字可以用htons()函数转换成网络数据格式的数字) struct in_addr sin_addr;// IP address in network byte order(Internet address) unsigned char sin_zero[8];// Same size as struct sockaddr没有实际意义,只是为了 跟SOCKADDR结构在内存中对齐 };*/ struct sockaddr_in client_name; // 数据类型"socklen_t"和int应该具有相同的长度.否则就会破坏 BSD套接字层的填充 socklen_t client_name_len = sizeof(client_name);//client_name的长度 pthread_t newthread;// pthread_t用于声明线程ID。sizeof(pthread_t) =8 server_sock = startup(&port); printf("httpd running on port %d\n", port);//套接字建立连接成功 while (1) { //接收一个套接字中已建立的连接 int accept(int sockfd,struct sockaddr *addr,socklen_t *addrlen); //sockfd, 利用系统调用socket()建立的套接字描述符,通过bind()绑定到一个本地地址(一般为服务器的套接字),并且通过listen()一直在监听连接; //addr, 指向struct sockaddr的指针,该结构用通讯层服务器对等套接字的地址(一般为客户端地址)填写,返回地址addr的确切格式由套接字的地址类别(比如TCP或UDP)决定;若addr为NULL,没有有效地址填写,这种情况下,addrlen也不使用,应该置为NULL; //addrlen, 一个值结果参数,调用函数必须初始化为包含addr所指向结构大小的数值,函数返回时包含对等地址(一般为服务器地址)的实际数值; //返回值 成功时,返回非负整数,该整数是接收到套接字的描述符;出错时,返回-1,相应地设定全局变量errno。 client_sock = accept(server_sock, (struct sockaddr *)&client_name, &client_name_len); if (client_sock == -1)//客户端接收失败 error_die("accept"); /* accept_request(&client_sock); */ //pthread_create() //第一个参数为指向线程标识符的指针。第二个参数用来设置线程属性。第三个参数是线程运行函数的起始地址。最后一个参数是运行函数的参数。 //返回值 若线程创建成功,则返回0。若线程创建失败,则返回出错编号, //创建线程成功后,新创建的线程则运行参数三和参数四确定的函数,原来的线程则继续运行下一行代码。 if (pthread_create(&newthread , NULL, (void *)accept_request, (void *)(intptr_t)client_sock) != 0) perror("pthread_create"); } close(server_sock); return(0); }
Tinyhttpd精读解析
HTTP服务器的本质:tinyhttpd源码分析及拓展