C Language Implementation Simple Web server

Source: Internet
Author: User
Tags sprintf

1http Brief Introduction

HTTP Hypertext Transfer Protocol: Host address: Port/url

Host is resolved to an IP address by the DNS server, so you can sometimes use the domain name directly,

HTTP default Access 80 port, HTTPS default Access 443 port


The general process is: After the browser enters the address, first establish a TCP connection with the Web server,

Then the browser sends the HTTP request message, the Web server responds to the message,

Then give him a response, and then the server actively disconnects.





2HTTP Request Message Format


The first one is the method of the request, and here's how:
Get,post,head,put,delete,options,trace,connect;


1GET

In the browser input URL, the browser will send a Get HTTP message request.

If you do not write the URL by default the "/" server can correspond to the page according to this response.

The header information contains some important request information, such as the host address.

Browser version, the phone's page is based on this to do.

The GET carry parameter is inside the URL, and the post is carried inside the package body.

The package body becomes body and the request head is called head.

Get pass parameters, format/url? username=xxx&passwd=bbb resolving parameter parts by question mark

The URL's pass-through parameters are limited, and each browser limit is different. URL does not allow carriage return line-wrapping



2POST

Post is also a request operation, and his data parameters are carried in the body of the HTTP request.

All parameters are not allowed to have the carriage return of the existence of a line, many times if you have to carry

To enter a line, you must first convert the data to Base64 encoding, because it does not have a carriage return to change. He is a common way to solve network transmission.





3HTTP Response Message Format



1 Status code: Success of request, status code description: Reason for success or failure

Sometimes access to a page will appear 404, this 404 is the status code.




4http Data transfer Mode

1 two important parameters in the transmission: written in the head surface

transfer-encoding:identity,chunked Which means the current body is a protocol .

Content-length:length: Length of packet



2Identity Direct send mode, length at the back of the data


3chunked mode, followed by each chunk package [Baotou, packet data]

Baotou: The first byte represents a Assic data, the second byte is also the Assic data

Two bytes combined to form a 16 binary data.

back two bytes, fixed 0d0a (carriage return line break) two bytes These 4 bytes are a chunk header,

The following packet is determined by the previous two bytes. The end flag for the packet is

0d 0a 30ASCLL code stands for 0.

That is, the end of the chunk package: is to meet a chunk equal to 0 end.

Then integrate this package to form the complete data.





5http Status Codes and tables

/*

{

[+] = "Continue",

[101] = "Switching Protocols",

[+] = "OK",

[201] = "Created",

[202] = "Accepted",

[203] = "non-authoritative Information",

[204] = "No Content",

[205] = "Reset Content",

[206] = "Partial Content",

[] = "Multiple Choices",

[301] = "Moved permanently",

[302] = "Found",

[303] = "See other",

[304] = "Not Modified",

[305] = "Use Proxy",

[307] = "Temporary Redirect",

[+] = "Bad Request",

[401] = "Unauthorized",

[402] = "Payment Required",

[403] = "Forbidden",

[404] = "Not Found",

[405] = "Method not Allowed",

[406] = "not acceptable",

[407] = "Proxy authentication Required",

[408] = "Request time-out",

[409] = "Conflict",

[410] = "Gone",

[411] = "Length Required",

[412] = "precondition Failed",

[413] = "Request Entity Too Large",

[414] = "Request-uri Too Large",

[415] = "Unsupported Media Type",

[416] = "Requested range not satisfiable",

[417] = "expectation Failed",

[+] = "Internal Server Error",

[501] = "Not Implemented",

[502] = "Bad Gateway",

[503] = "Service unavailable",

[504] = "Gateway time-out",

[505] = "HTTP Version not supported",

}

*/





6 use Http_parmer to parse the URL read and return it to the client

Parse our HTTP message http_parser p;http_parser_init (&p,http_request); http_parser_settings s;http_parser_ Settings_init (&s);//resolves to url  callback s.on_url = ws_on_url;//resets parsing information init_ws_params ();//parser execution. Returns the parsed number of bytes http_parser_execute (&p,&s,http_req,len);//sets the callback function switch  (P.method)   //the way the message responds { Case http_get:{int len_url = filter_url (Ws_http.url);//access to the webpage   if  (strncmp (" /",  ws_http.url, len_url)  == 0) { //Access Test this htmlstrncpy (ws_http.url, " www_root/ Index.html ",  strlen (" www_root/index.html "));} else if  (strncmp ("/test",  ws_http.url, len_url)  == 0) { //access to the default url  root directory strncpy (ws_http.url,  "www_root/test.html",  strlen ("www_root/test.html"));} Char* file_data = open_files (Ws_http.url);//delivery paper    that is, response client//Release memory free (file_data);} Break;case http_post:break;} endprintf ("\ n"); Read file Static char* open_files (char* filename) {//Read this file File* f = fopen (filename, "RB");//File Size Int file_size = 0;fseek (f,0,seek_end ); File_size = ftell (f);//pointer to file header fseek (f, 0, 0); Char* file_data = malloc ( file_size + 1); fread (file_data, file_size,1, f); File_data[file_size] = 0;fclose ( f); return file_data;}




7 Response Request Message

Use identity to send response message static voidwrite_ok_identity (int sock, char* body) {int len = strlen (body);//Use Direct mode transfer-encoding:identitychar* send_line = malloc (len + 8096), memset (send_line, 0, sizeof (send_line));// Response HTTP Header sprintf (send_line, "http/1.1%d%s\r\n", "OK");//Set the head of some information such as transfer mode body length char* walk = send_line;//Skip this head wal  K = walk + strlen (walk), sprintf (Walk, "transfer-encoding:%s\r\n", "Identity"),//body length walk = walk + strlen (walk); Head End sprintf (Walk, "Content-length:%d\r\n\r\n0", Len);//write data section walk = walk + strlen (walk); sprintf (Walk, "%s", body);// Send message response to client send (sock, Send_line, strlen (Send_line), 0); free (send_line); walk = NULL;}





C Language Implementation Simple Web server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.