luigi
luigi

Reputation: 3

C-code, simple web server (Code OK)

I have a problem with my code about web server

#include<netinet/in.h>    
#include<stdio.h>    
#include<stdlib.h>    
#include<sys/socket.h>    
#include<sys/stat.h>    
#include<sys/types.h>    
#include<unistd.h>    

int main() {    
   int create_socket, new_socket;    
   socklen_t addrlen;    
   int bufsize = 1024;    
   char *buffer = malloc(bufsize);    
   struct sockaddr_in address;    

   if ((create_socket = socket(AF_INET, SOCK_STREAM, 0)) > 0){    
      printf("The socket was created\n");
   }

   address.sin_family = AF_INET;    
   address.sin_addr.s_addr = INADDR_ANY;    
   address.sin_port = htons(15000);    

   if (bind(create_socket, (struct sockaddr *) &address, sizeof(address)) == 0){    
      printf("Binding Socket\n");
   }


   while (1) {    
      if (listen(create_socket, 10) < 0) {    
         perror("server: listen");    
         exit(1);    
      }    

      if ((new_socket = accept(create_socket, (struct sockaddr *) &address, &addrlen)) < 0) {    
         perror("server: accept");    
         exit(1);    
      }    

      if (new_socket > 0){    
         printf("The Client is connected...\n");
      }

      recv(new_socket, buffer, bufsize, 0);    
      printf("%s\n", buffer);    
      write(new_socket, "hello world\n", 12);    
      close(new_socket);    
   }    
   close(create_socket);    
   return 0;    
}

this is a little code to create a web server that at the port 15000 reply with "hello wordl" . Now i would that my server at a request (for example) "http://127.0.0.1:15000/luigi" reply with the text "luigi",that is with the phrase after " / ". Thanks!

Upvotes: 0

Views: 229

Answers (2)

vvvv
vvvv

Reputation: 135

To add up to what user3864685 said, you can use 'strtok' function to get the string after "GET /".

Upvotes: -1

Ashwani
Ashwani

Reputation: 2052

After recv function, you will have something like

GET /luigi HTTP/1.1

in buffer.This is the request sent by browser.
Text after GET is the relative url to your base address (127.0.0.1:15000). Now you can parse the buffer and do whatever you want.You can go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html for more details.

Upvotes: 2

Related Questions