SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
WEB
          SERVERS
                     Using C Language

Sujeet Kumar Singh
Web Developer

                         Web Server  Using C Language   1
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Web Server  Using C Language   25

Contenu connexe

Tendances

File Transfer Protocol
File Transfer ProtocolFile Transfer Protocol
File Transfer ProtocolOm Prakash
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unixswtjerin4u
 
Common gateway interface
Common gateway interfaceCommon gateway interface
Common gateway interfaceAnandita
 
Microsoft Exchange 2013 architecture
Microsoft Exchange 2013 architectureMicrosoft Exchange 2013 architecture
Microsoft Exchange 2013 architectureMotty Ben Atia
 
Subversion in 2010 and Beyond
Subversion in 2010 and BeyondSubversion in 2010 and Beyond
Subversion in 2010 and Beyondguest1243d91
 
Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)maamir farooq
 
Slides serverside main
Slides serverside mainSlides serverside main
Slides serverside mainggunasagar
 
FTP Client and Server | Computer Science
FTP Client and Server | Computer ScienceFTP Client and Server | Computer Science
FTP Client and Server | Computer ScienceTransweb Global Inc
 
12 coms 525 tcpip - applications - http - telnet
12   coms 525 tcpip - applications - http - telnet12   coms 525 tcpip - applications - http - telnet
12 coms 525 tcpip - applications - http - telnetPalanivel Kuppusamy
 
File transfer protocol (ftp)
File transfer protocol (ftp)File transfer protocol (ftp)
File transfer protocol (ftp)Cort1026
 
02.28.13 WANDisco SVN Training: Getting Info Out of SVN
02.28.13 WANDisco SVN Training: Getting Info Out of SVN02.28.13 WANDisco SVN Training: Getting Info Out of SVN
02.28.13 WANDisco SVN Training: Getting Info Out of SVNWANdisco Plc
 
file transfer and access utilities
file transfer and access utilitiesfile transfer and access utilities
file transfer and access utilitiestumetr1
 
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
CS8651   Internet Programming - Basics of HTML, HTML5, CSSCS8651   Internet Programming - Basics of HTML, HTML5, CSS
CS8651 Internet Programming - Basics of HTML, HTML5, CSSVigneshkumar Ponnusamy
 

Tendances (20)

Web technologies: HTTP
Web technologies: HTTPWeb technologies: HTTP
Web technologies: HTTP
 
File Transfer Protocol
File Transfer ProtocolFile Transfer Protocol
File Transfer Protocol
 
Http request&response
Http request&responseHttp request&response
Http request&response
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
Common gateway interface
Common gateway interfaceCommon gateway interface
Common gateway interface
 
HTTP & HTML & Web
HTTP & HTML & WebHTTP & HTML & Web
HTTP & HTML & Web
 
CGI Presentation
CGI PresentationCGI Presentation
CGI Presentation
 
Microsoft Exchange 2013 architecture
Microsoft Exchange 2013 architectureMicrosoft Exchange 2013 architecture
Microsoft Exchange 2013 architecture
 
Subversion in 2010 and Beyond
Subversion in 2010 and BeyondSubversion in 2010 and Beyond
Subversion in 2010 and Beyond
 
Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)
 
Slides serverside main
Slides serverside mainSlides serverside main
Slides serverside main
 
FTP Client and Server | Computer Science
FTP Client and Server | Computer ScienceFTP Client and Server | Computer Science
FTP Client and Server | Computer Science
 
12 coms 525 tcpip - applications - http - telnet
12   coms 525 tcpip - applications - http - telnet12   coms 525 tcpip - applications - http - telnet
12 coms 525 tcpip - applications - http - telnet
 
File transfer protocol (ftp)
File transfer protocol (ftp)File transfer protocol (ftp)
File transfer protocol (ftp)
 
02.28.13 WANDisco SVN Training: Getting Info Out of SVN
02.28.13 WANDisco SVN Training: Getting Info Out of SVN02.28.13 WANDisco SVN Training: Getting Info Out of SVN
02.28.13 WANDisco SVN Training: Getting Info Out of SVN
 
Http protocol
Http protocolHttp protocol
Http protocol
 
file transfer and access utilities
file transfer and access utilitiesfile transfer and access utilities
file transfer and access utilities
 
CGI Introduction
CGI IntroductionCGI Introduction
CGI Introduction
 
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
CS8651   Internet Programming - Basics of HTML, HTML5, CSSCS8651   Internet Programming - Basics of HTML, HTML5, CSS
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
 
Cgi
CgiCgi
Cgi
 

Similaire à Web server

MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenVannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxalfredacavx97
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009Cathie101
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Computer networking mcis 6163 project
Computer networking mcis 6163 projectComputer networking mcis 6163 project
Computer networking mcis 6163 projectAnakinzs
 
Ch 22: Web Hosting and Internet Servers
Ch 22: Web Hosting and Internet ServersCh 22: Web Hosting and Internet Servers
Ch 22: Web Hosting and Internet Serverswebhostingguy
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagarNitish Nagar
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxkacie8xcheco
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docxhanneloremccaffery
 
009577496.pdf
009577496.pdf009577496.pdf
009577496.pdfEidTahir
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side ProgrammingMilan Thapa
 

Similaire à Web server (20)

MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)
 
Computer networking mcis 6163 project
Computer networking mcis 6163 projectComputer networking mcis 6163 project
Computer networking mcis 6163 project
 
Ecom 1
Ecom 1Ecom 1
Ecom 1
 
Ch 22: Web Hosting and Internet Servers
Ch 22: Web Hosting and Internet ServersCh 22: Web Hosting and Internet Servers
Ch 22: Web Hosting and Internet Servers
 
03 sockets
03 sockets03 sockets
03 sockets
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagar
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
009577496.pdf
009577496.pdf009577496.pdf
009577496.pdf
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
java networking
 java networking java networking
java networking
 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Servlet
ServletServlet
Servlet
 

Web server

  • 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