1. WEB
SERVERS
Using C Language
Sujeet Kumar Singh
Web Developer
Web Server Using C Language 1
2. Introduction to Web Server
The primary function of a web server is to deliver web pages on the request to
clients. This means delivery of HTML documents and any additional content that
may be included by a document, such as images, style sheets and scripts.
A user agent, commonly a web browser or web crawler, initiates communication
by making a request for a specific resource using HTTP and the server responds
with the content of that resource or an error message if unable to do so The
so.
resource is typically a real file on the server's secondary memory, but this is not
necessarily the case and depends on how the web server is implemented.
Request
Web
Web
Client
Response Server
Web Server Using C Language 2
3. Request and Response header
A full request can contain more than one line, and a blank line must be sent at the end to
q
signify the end of the request.
GET /index.html HTTP/1.0
Host: www paulgriffiths net
www.paulgriffiths.net
User-Agent: Lynx/2.8.1rel.2 libwww-FM/2.14
Accept-Encoding: gzip, compress
Accept-Language: en
<BLANK LINE>
A response generated by the web server may be look like as shown below. A blank
A response generated by the web server may be look like as shown below A blank
line must be sent at the end to signify the end of the request.
HTTP/1.0 200 OK
Server: PGWebServ v0.1
Content-Type: text/html
<BLANK LINE>
Web Server Using C Language 3
4. Socket Programming in C
Socket programming is used to connect two process
running on two different host in a networking which
have an host address through a specified port
port.
A socket address is a combination of host address of
the host and port address used by it.
Socket Address=Host Address+ Port Address
Web Server Using C Language 4
5. Primary Header Files used in Socket Programming
Include file sequence may affect processing (order is important!)
<sys/types.h> - prerequisite typedefs
<errno.h> - names for “errno” values (error numbers)
<sys/socket.h> - struct sockaddr; system prototypes and constants
<netdb.h.h> - network info lookup prototypes and structures
<netinet/in.h> - struct sockaddr_in; byte ordering macros
<arpa/inet.h> - utility function prototypes
Web Server Using C Language 5
6. Various Steps in Development of Web Server in C
HTTP is essentially a text‐based protocol which runs over TCP/IP (though it can
HTTP i ti ll t t b d t l hi h TCP/IP (th h it
run over any transport protocol). The essential network steps are:
Create a listening socket
Accept a connection with it
p
Fork a child process to service the connection, while the parent process
goes back to accept more connections.
Read in the HTTP request
Send the HTTP response
Send the entity requested (e.g. an HTML document)
Send the entity requested (e g an HTML document)
Web Server Using C Language 6
7. Various Function of Web Server in C
Various C functions (user defined function) which are important for
V i C f ti ( d fi d f ti ) hi h i t tf
implementation of a web server are as follows:
log()
Logs messages to a log file. If the user requests an operation from
the Web server that is not allowed or can't be completed, then web server
tries to inform the user directly. This is done by returning a fake Web page to
the user that includes the error message. Since this function is only called
from the child Web server process, the function can (once completed) exit
and the main Web server process continues to allow further browser
connection requests. If this is not a recoverable error, then the process is
stopped.
web()
Deals i h h
D l with the HTTP b browser request and returns the d
d h data to the
h
browser. This function is called in a child process ‐‐ one for each Web request.
It also allows the main Web server process to continue waiting for more
connections. Checks are made to ensure the request is safe and can be
q
completed. After the checks have been made, it transmits the requested static
file to the browser and exits.
Web Server Using C Language 7
8. Various Function of Web Server in C
Various C functions (user defined function) which are important for
V i C f ti ( d fi d f ti ) hi h i t tf
implementation of a web server are as follows:
main()
This is the main Web server process function. After checking the
command parameters, it creates a socket for incoming browser requests, sits
in a loop accepting requests, and starts child processes to handle them. It
should never end.
Web Server Using C Language 8
9. Pseudo Code for the Functions
Pseudo code for the log() function is follows:
Pseudo code for the log() function is follows:
log()
{
outputs error, sorry or log messages to the web
server.log file
if a sorry message, t
transmit it t th b
it to the browser as a f k
fake
HTML response
if error or sorry message the p g
y g program is stopped
pp
}
Web Server Using C Language 9
10. Pseudo Code for the Functions
Pseudo code for the web() function is follows:
Pseudo code for the web() function is follows:
web() - this function returns the request back to the
browser
{
read from the socket the HTTP request
check it’s a simple GET command
check no parent di
h k t directory requested t escape th web
t t d to the b
servers home directory
if no file name given assume index.html
check the file extension is valid and supported
pp
check the file is readable by opening it
transmit the HTTP header to the browser
transmit the file contents to the browser
if LINUX sleep for one second to ensure the data arrives
at the browser
Stop
}
Web Server Using C Language 10
11. Pseudo Code for the Functions
Pseudo code for the main() function is follows:
Pseudo code for the main() function is follows:
main()
{
check the directory supplied is sensible and not a
security risk
become a d
b daemon process
ignore child programs (to avoid zombies when child
processes stop)
create a socket, bind it to a p
, port number and start
listening to the socket
forever {
wait and accept incoming socket connection
fork a child process
if the child process then call the web function
else close new connection
}
}
Web Server Using C Language 11
12. System Calls
Various system calls involved in request/response processes both at client
Various system calls involved in request/response processes both at client
and server side are as follows:
Server Parent Client
socket():Service socket():Service
bind():Port number connect():Start
listen():ready write() & read()
forever
{
accept():wait for request
fork():create child Server Child
} write() & read()
write() & read()
Web Server Using C Language 12
13. Socket System Calls
The socket() bind() listen() and accept() network system calls all work
socket(), bind(), listen(),
together to create a server process. They set up a socket ready for use to
communicate over a network when combined. A socket is:
An input and output stream ‐‐ regular pipes and files, for example.
Remote access to or from a server ‐‐ when used over a network.
Bidirectional ‐‐ when you read and write the same socket at both ends.
Regular read and write functions ‐‐ used to send and receive data.
A stream (no natural structure) ‐‐ you have to decide the protocol.
A stream (no natural structure) you have to decide the protocol
For HTTP ‐‐ the request message and response message are finished with a
carriage return (CR or /r in C code) and a line feed (LF and /n in C code). The
URL is terminated by a space character and the end of the requested file is
highlighted by closing the socket. There are more complex alternatives in
HTTP and many optional features, but this is the simplest way to do it.
Web Server Using C Language 13
14. Socket System Calls : socket()
The socket() function creates the socket and returns the file descriptor which
descriptor,
can be used with any function that uses file descriptors, such as read, write,
and close. The arguments tell the operating system what type of socket and
communication you need.
/* Create socket */
listener = socket(AF_INET, SOCK_STREAM, 0)
Note:‐
listener is an integer type variable
listener is an integer type variable
AF_INET, SOCK_STREAM are constants
Web Server Using C Language 14
15. Socket System Calls : bind()
The bind() function attaches a particular port number to the socket When a
socket.
client is trying to contact your server, it will use the IP address (often found by
using a DNS service to convert a hostname to an IP address) and the port
number. The port number tells the operating system which service you want
on the server.
/* Assign socket address to socket */
bind(listener, (struct sockaddr *) &servaddr, sizeof(servaddr)
Note:‐
sockaddr is a struct defined in socket h
is a struct defined in socket.h
servaddr is struct type variable of sockaddr_in
Web Server Using C Language 15
16. Socket System Calls : listen()
The listen() function call tells the operating system you are now ready to
accept incoming requests. This is the final switch that makes the socket
available to local and remote programs.
/* Make socket a listening socket */
listen(listener, LISTENQ)
Note:‐
LISTENQ is a constant
LISTENQ is a constant
Web Server Using C Language 16
17. Socket System Calls : accept()
The accept() function does not return to your program until there is a socket
connection request to this IP address and port number. The accept() function
uses the file descriptor of the socket, but a new structure for the incoming
connection (struct sockaddr in) allows a server to check who is connecting to
sockaddr_in)
it.
/* Wait for connection */
(conn = accept(listener, NULL, NULL)
Note:‐
conn is an integer type variable
is an integer type variable
Web Server Using C Language 17
18. Other System Calls
The fork() open() read() write() and close() are some other system calls
fork(), open(), read(),
used for some other jobs. Fork() is used to create a sub process or a child
process. Open(), read() and write() is work with the requested file by the
client. Close() is used to close the open connections.
Web Server Using C Language 18
19. Other System Calls:fork()
Starts a child process In the parent it returns the process id (PID) of the
process. parent,
child, and in the child, it returns zero.
/* Fork child process to service connection */
pid = fork()
Note:‐
pid is an integer type variable
is an integer type variable
Web Server Using C Language 19
20. Other System Calls:open()
It is used to open the requested file by the client
client.
/* Open the directory server_root */
open(server_root, O_RDONLY);
Note:‐
Server_root is a constant specifying the root directory.
Server root is a constant specifying the root directory
O_RDONLY is a open mode.
Web Server Using C Language 20
21. Other System Calls:read()
It is used to read the requested file by the client It is used by both client as
client.
well as server to read files.
/* Reading the resource*/
read(resource, &c, 1))
Note:‐
Resouce is a contant specifying the resource name
is a contant specifying the resource name
c is char type variable
1 is the read mode Web Server Using C Language 21
22. Other System Calls:write()
It is used to write the requested file by the client It is used by both client as
client.
well as server to write files.
/* Writing to the connection */
write(conn, &c, 1)
Note:‐
conn is an integer type constant representing accepted connection
is an integer type constant representing accepted connection.
c is char type variable
1 is the read mode Web Server Using C Language 22
23. Other System Calls:close()
It is used to close the listening socket and connected socket
socket.
/* Close listening socket*/
close(listener)
/* Close connected socket and exit */
close(conn)
Web Server Using C Language 23
24. Sample TCP Client/Server Session
Various socket system calls called at both server and client at different levels
are shown below:
Iterative Server
socket() Remote Client
bind() socket()
listen() gethostbyname()
accept() connect()
recv()/send() recv()/send()
close() close()
Web Server Using C Language 24