Introduction to the principle of original statement:
This address is http://blog.csdn.net/zhujunxxxxx/article/details/40658925 reproduced please indicate the source. Author contact email [email protected]
How the HTTP protocol works
Connection: The Web browser establishes a connection to the Web server and opens a virtual file called a socket (socket), which establishes a successful connection establishment.
Request: The Web browser submits a request to the Web server through a socket. HTTP requests are typically GET or post commands (the post is used for the pass of the form parameter). The format of the Get command is:
GET path/file name http/1.0
The file name indicates which files are accessed, and http/1.0 indicates the HTTP version used by the Web browser.
Answer: After the Web browser submits the request, it is routed to the Web server via the HTTP protocol. After the Web server is received, the transaction is processed, and the results are passed back to the Web browser via HTTP to display the requested page on the Web browser.
Code implementation in fact, the Web server is a generic socket server, but it complies with the HTTP protocol to achieve it
server.c////David J. malan//[email protected]////feature test Macro Requirements#define _gnu_source#define _ Xopen_source 700#define _xopen_source_extended//limits on a HTTP request ' s size, based on Apache ' s//Http://httpd.apache . org/docs/2.2/mod/core.html#define limitrequestfields 50#define limitrequestfieldsize 4094#define LimitRequestLine 8190//number of octets for buffered reads#define octets 512//header files#include <stdio.h> #include <arpa/inet. h> #include <errno.h> #include <limits.h> #include <math.h> #include <signal.h> #include < stdbool.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> Typestypedef Char octet;//prototypesbool connected (void), bool error (unsigned short code), void handler (int signal); ssize_t load (void), const char* Lookup (const char* extension), ssize_t parse (void), void reset (void), void start (short port , const char* path); void stop (void);//server ' s Rootchar* root = null;//file descriptor for Socketsint cfd =-1, sfd = -1;//buffer for requestoctet* request = null;//file Po Inter for filesfile* file = null;//buffer for response-bodyoctet* BODY = null;int Main (int argc, char* argv[]) {//a Globa L variable defined in errno.h it ' s "set by system//calls and some library functions [to a nonzero value]//in the event Of an error to indicate what went wrong "errno = 0;//default to a random portint port = 0;//usageconst char* usage =" Us Age:server [-P port]/path/to/root ";//Parse Command-Line argumentsint opt;while ((opt = getopt (argc, argv," HP: "))!! =-1 {switch (opt) {//-hcase ' h ':p rintf ("%s\n", usage), return 0;//-P portcase ' p ':p ort = atoi (optarg); break;}} Ensure Port is a non-negative short and path to server's root is specifiedif (Port < 0 | | port > Shrt_max | | argv [Optind] = = NULL | | Strlen (Argv[optind]) = = 0) {//Announce usageprintf ("%s\n", usage);//return 2 just like bash ' s Builtinsreturn 2;} Start ServerStart (Port, aRgv[optind]);//Listen for SIGINT (aka CONTROL-C) signal (SIGINT, handler);//Accept connections one at a timewhile (true) {/ /reset server ' s statereset ();//wait until client is CONNECTEDIF (connected ()) {//Parse client ' s HTTP requestssize_t octe TS = Parse (); if (octets = =-1) {continue;} Extract request ' s request-line//http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.htmlconst char* haystack = request;char* needle = strstr (haystack, "\ r \ n"), if (needle = = NULL) {error (n); continue;} else if (Needle-haystack + 2 > Limitrequestline) {error (414); continue;} Char Line[needle-haystack + 2 + 1];strncpy (line, haystack, Needle-haystack + 2); Line[needle-haystack + 2] = ' + ';// Log request-lineprintf ("\n%s", line);//todo:validate request-linechar* method = line;char* request_target;char* version;char* absolute_path;char* s1;s1 = strstr (line, ""); if (S1 = = NULL | | (Version = STRSTR (S1 + 1, "")) = = NULL | | STRNCMP (line + sizeof)-2, "\ r \ n", 2) = = 0) {error]; continue;} Request_target = StrDup (S1 + 1); Request_target[version-s1-1] = ' request_target ';//printf ("is%s, version is%s", Request_targe T, version), if (strncmp (method, "GET", 3)! = 0) {error (405); continue;} if (strncmp (Request_target, "/", 1)! = 0) {error (501); continue;} if (STRCHR (request_target, ' \ "')! = NULL) {error (n); continue;} if (strncmp (version + 1, "http/1.1", 8)! = 0) {error (505); continue;} if (STRCHR (Request_target, '. ') = = NULL) {error (501); continue;} Todo:extract Query from Request-targetchar *query = STRCHR (Request_target, '? '); if (query = = NULL) query = ""; elsequery = query + 1;//printf ("Query is%s\n", query);//todo:concatenate Root and absolute -pathabsolute_path = StrDup (request_target);//printf ("%s.%d\n", Absolute_path, Query-request_target); if (strcmp ( Query, "")! = 0) Absolute_path[query-request_target-1] = ' + ';//printf ("Absolute path is%s\n", Absolute_path); Char *pa th = (char*) malloc, strcpy (path, root),//strcat (Path, "/"), strcat (Path, Absolute_path),//printf ("Path is%s\n", path);//todo:ensure Path Existsif (Access (path, F_OK) = = 1) {error (404); continue;} Todo:ensure path is Readableif (Access (path, R_OK) = = 1) {error (403); continue;} Todo:extract path ' s extensionchar* extension;if ((Extension = STRRCHR (Absolute_path, '. ')) = = NULL) {error (501); Contin UE;} Extension = extension + 1;//printf ("extension is%s\n", extension);//Dynamic Contentif (strcasecmp ("php", extension) = = 0 ) {//Open pipe to PHP interpreterchar* format = "query_string=\"%s\ "redirect_status=200 script_filename=\"%s\ "php-cgi"; Char command[strlen (format) + (strlen (path)-2) + (strlen (query)-2) + 1];sprintf (command, format, query, path); file = P Open (Command, "R"), if (file = = NULL) {error ($); continue;} Load filessize_t size = load (); if (size = =-1) {error ($); continue;} Subtract php-cgi ' s headers from body's size to get content ' s lengthhaystack = Body;needle = Memmem (haystack, size, "\r\ N\r\n ", 4); if (needle = = NULL) {error ($); continue;} size_t length = size-(needle-hayStack + 4);//Respond to Clientif (dprintf (CFD, "http/1.1 ok\r\n") < 0) {continue;} if (dprintf (CFD, "connection:close\r\n") < 0) {continue;} if (dprintf (CFD, "Content-length:%i\r\n", Length) < 0) {continue;} if (write (CfD, body, size) = =-1) {continue;}} Static contentelse{//look up file ' s MIME typeconst char* type = lookup (extension), if (type = = NULL) {error (501); Continu e;} Open Filefile = fopen (path, "R"), if (file = = NULL) {error ($); continue;} Load filessize_t length = load (); if (length = =-1) {error ($); continue;} Todo:respond to client//respond with status-linedprintf (CFD, "http/1.1 ok\r\n");//respond with Connection header dprintf (CFD, "connection:close\r\n");//Respond with Content-length headerdprintf (CFD, "Content-length:%i\r\n", length);//Respond with Content-type headerdprintf (CFD, "content-type:text/html\r\n");//Respond with crlfdprintf (CFD, "\ r \ n"); write (CfD, body, length);} Announce okprintf ("\033[32m");p rintf ("http/1.1 OK");p rintf ("\033[39m\n ");}}} /** * Accepts a connection from a client, blocking (i.e., waiting) until one is heard. * Upon success, returns true; Upon failure, returns false. */bool connected (void) {struct sockaddr_in cli_addr;memset (&cli_addr, 0, sizeof (CLI_ADDR)); socklen_t Cli_len = sizeof (CLI_ADDR), cfd = Accept (sfd, (struct sockaddr*) &cli_addr, &cli_len); if (cfd = =-1) {return false;} return true;} /** * Handles Client errors (4xx) and server errors (5xx). */bool error (unsigned short code) {//Ensure client's socket is openif (cfd = =-1) {return false;} Ensure code is within RangeIf (Code < | | code > 599) {return false;} Determine Status-line ' s phrase//http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1const char* phrase = Null;switch (code) {Case 400:phrase = ' bad Request '; break;case 403:phrase = "Forbidden"; break;case 404:phrase = "Not F Ound "; Break;case 405:phrase = "Method not allowed"; Break;case 413:phrase = "Request Entity Too Large"; Break;case 414:phrase= "Request-uri Too Long"; Break;case 418:phrase = "I ' m a teapot"; Break;case 500:phrase = "Internal Server Error"; Break;case 501:phrase = "not implemented"; Break;case 505:phrase = "HTTP Version not supported"; break;} if (phrase = = NULL) {return false;} templatechar* template = "
Compilation method
Gcc-o Server Server.c-lm
How to Run
./server-p 8080 Public
Where the public directory is stored in HTML and PHP files
C Language Implementation PHP server