Sie sind auf Seite 1von 6

/*HttpServer.

c */

/* Author: baddie
 * This program is a http server
 * It sends a web page to the browser(client)
 * User submits a value in the text box 
 * this value is got by the server
 * It resends the webpage to the client
 * with history of messages submitted by
 * the user so far
 
 * NOTE: URL is http://urserver:urportnumber
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

// prototypes
char *substring(size_t, size_t, const char *, char *, size_t);
char hexToAscii(char, char);

//========================================================================
================================

int main()
{
        int sock, connected, bytes_recieved , true = 1;  
        char recv_data[1024]; // for received messages from client
        char send_data[1024]; // for msgs to be sent to the client
        struct sockaddr_in server_addr,client_addr;    
        int sin_size, i = 0, j=0;
         char a[100];
        char *equal_pos;
int  str_len;
char extract_text[100], extract[100];
        char msg_table[50][1000]; //DS where msgs are stored
int start, msgCount = 0,count = 0;
        int first =0; //for the 1st time the page is displayed        
        int next = 0; //for future 
//create a socket
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == ­1) {
            perror("Socket");
            exit(1);
        }

        if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == ­1) {
            perror("Setsockopt");
            exit(1);
        }
        // designate port number
        server_addr.sin_family = AF_INET;         
        server_addr.sin_port = htons(5485);     
        server_addr.sin_addr.s_addr = INADDR_ANY; 
        bzero(&(server_addr.sin_zero),8); 

        if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))
                                                                       == ­1) {
            perror("Unable to bind");
            exit(1);
        }
   
        //listen for client requests
        if (listen(sock, 5) == ­1) {
            perror("Listen");
            exit(1);
        }

        
printf("\nHTTPServer Waiting for client on port 5485");
        fflush(stdout);

        while(1)
        {  

            sin_size = sizeof(struct sockaddr_in);
            connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);
            printf("\n­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
            printf("\n I got a connection from (%s , %d)",
            inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

            while (1)
            {
  if(first == 0) //write an else part where next should be 1        
         { 
// html code for the webpage 
        strcpy(send_data, "<html><head></head><body bgcolor = 
lavender><br><H1><center>MESSAGING SYSTEM</center></H1> <br> <br> <center>enter 
comments in text box </center> <br> <br> <br> <form method = post action = 
http://agate.cs.unh.edu:5485>" "<center><input name = comment type = text value = " " > <br><br> 
<input type = submit value = submit></center> <br><br><h3><b><center> Message 
History</center></b></h3>");
                 // left over html code ­ closing tags 
strcat(send_data, "</form> </body> </html>");                    
                 printf("\n page sent");
       // send the html code to the browser
                 send(connected, send_data,strlen(send_data), 0); 
fflush(stdout); 
first = 1;
         }       
               // data from client is got­ will  have the header and the info user entered in text box
                /*for(i =0 ;i<1024;i++){
recv_data[i] = '\0';
       }*/
  
/*else { 
first = 1;
next = 1;
 }*/

                bytes_recieved = recv(connected,recv_data,1024,0);
                  recv_data[bytes_recieved] = '\0';

  //print the received data
  //various header lines from the browser will be displayed
  //followed by user typed value in the text box
  //name of the text box is comment
  //so the last line in the information sent by the client will be
  //comment = user submitted value

                  printf("\n RECIEVED DATA = %s " , recv_data);
          equal_pos = strrchr(recv_data,'='); //last occurance of =
        printf("\n the last occurence of '=' is %d \n", equal_pos ­ recv_data + 1);
      
                 start = equal_pos ­ recv_data + 1;
                  str_len = strlen(recv_data);
                  printf("\n length of the recv_data is: %d ", str_len);                    
                  printf("\n user text is: %s \n", substring(start,10,recv_data,extract_text,sizeof extract_text));
              
                  printf("\n The text user entered is: %s", extract_text);     
                  //check if the string has some + if so replace it with a ' '
                  j=0; i=0;

  // user entered text can contain space, special characters 
    // space will be sent to the server as +
    // special characters will be sent as %corresponding hexa value
    // so the user's value has to be parsed and restored with 
    // corresponding characters

                     while(i<strlen(extract_text)) {

if(extract_text[i] == '+') {
 
   printf("\n space detected");
   extract[j] = ' ';
              i++;                         
}
else if(extract_text[i] == '%') {
    
     printf("\n special character detected");
       extract[j] = hexToAscii(extract_text[i+1],extract_text[i+2]);
     i = i+3;
 }    
                              
else {
   // normal character. so copy it simply
   extract[j] = extract_text[i];
   i++;
}
j++;

     } 

extract[j] ='\0';
                 
        strcpy(msg_table[msgCount],extract);         
               printf(" \n msg_table info is %s", msg_table[msgCount]);
                       msgCount++;  //increment number of messages 
             
              //store it in the msg_array
            
              for(count = 0 ; count< msgCount; count++) {
                      printf( "\n msgs: %s",msg_table[count]);                
                } 
              
              fflush(stdout);

 // after the 1st time, no more empty page will be sent
 // every time the page is sent to the browser
 // the msgs in msgtable has to be returned

         if(first == 1) {
strcpy(send_data," ");
               strcat(send_data, "<html><head></head><body bgcolor = 
lavender><br><H1><center>MESSAGING SYSTEM</center></H1> <br> <br> <center>enter 
comments in text box </center> <br> <br> <br> <form method = post action = 
http://agate.cs.unh.edu:5485>" "<center><input name = comment type = text value = " " > <br><br> 
<input type = submit value = submit></center> <br><br><h3><b><center> Message 
History</center></b></h3>");

                // write to the browser previous messages
                   for(count = 0; count < msgCount; count++) {
                        strcat(send_data, "<br/>");
                        strcat(send_data, msg_table[count]);
                   }             
                  // left over html code ­ closing tags 
                  strcat(send_data, "</form> </body> </html>");                      

                  printf("\n page sent");

  //send the page and history of messages to the browser
                  send(connected, send_data,strlen(send_data), 0);

                  close(connected);
                  break;
              }

        }       
      }
      close(sock);
      
      return 0;
}

//========================================================================
================================= 
/* This function extracts the value user
 * entered in the text box
 */
 
  char *substring(size_t start, size_t stop, const char *src, char *dst, size_t size)
{
   int count = stop ­ start;
   if ( count >= ­­size )
   {
      count = size;
   }
   sprintf(dst, "%.*s", count, src + start);
   return dst;
}

//========================================================================
================================
 
/* special characters like %, $ will be sent as hexadecimal
 * by the browser. server should interpret the correct spl char 
 * This function converts hex codes to char
 */

 char hexToAscii(char first, char second)
 {
char hex[5], *stop;
hex[0] = '0';
hex[1] = 'x';
hex[2] = first;
hex[3] = second;
hex[4] = 0;
return strtol(hex, &stop,16);

 }

Das könnte Ihnen auch gefallen