Creating a simple webserver using sockets
I have the following code for server in C. The web browser will serve as
the client. So far, what I know is I need to run the executable file from
the terminal and open a web browser and type: localhost:54321 . 54321 is
port number where we need to run the web server. The next thing we need to
do is parse the http request received from the web browser and obtain the
name of the object requested. I know how to parse but I don't know how to
receive the object. Should I use form inputs to get the name of the
object? Thanks! Just a newbie in socket programming and I am only able to
create sockets.
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int listenfd,connfd;
struct sockaddr_in servaddr,cliaddr;
socklen_t len = sizeof(cliaddr);
char cli_ip[32];
char mesg[1024];
listenfd = socket(PF_INET,SOCK_STREAM,0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(54321);
if ( bind( listenfd, (struct sockaddr*) &servaddr, sizeof(servaddr) ) <
0 ){
perror(NULL);
exit(-1);
}
//not present in udp server
listen(listenfd,2);
while(1){
//not present in udp server
connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&len);
inet_ntop(AF_INET,(struct in_addr *) &cliaddr.sin_addr, cli_ip,
sizeof(cli_ip) );
printf("Client %s connected. \n",cli_ip);
while(1){
memset(mesg,0,sizeof(mesg));
if( recvfrom(connfd,mesg,sizeof(mesg),0,(const struct sockaddr
*)&cliaddr,&len) > 0 ){
printf("From %s port %d:
%s",cli_ip,ntohs(cliaddr.sin_port),mesg);
}
else {
printf("Client %s disconnected. \n",cli_ip);
break;
}
}
close(connfd);
}
close(listenfd);
return 0;
}
We were then also given a sample response if the user sends index.html:
GET /index.html HTML/1.1
Host: localhost:54321
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101
Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
No comments:
Post a Comment