[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 740
  • Last Modified:

Socket programming

Can any one help me? am trying to write a socket for unix. Upon connection with a browser as a client, it should display a web page on the browser. can any got any idea how to to that? The language i want to use is C.
0
pritam123456
Asked:
pritam123456
  • 10
  • 10
1 Solution
 
sunnycoderCommented:
Hi pritam123456,

this says it better than anything else
http://www.ecst.csuchico.edu/~beej/guide/net/html/

I highly recommend this tutorial ... Go through it from front to back and you will face no problems with socket programming.

Towards the end it has some source code for TCP server and client ... You need to modify the server to send out html page instead of a simple string ... everything else remains more or less the same ...

If you are thinking of building a webserver, then there is more work involved that just socket programming ... I would suggest looking into apache source code

Sunnycoder
0
 
pritam123456Author Commented:
yes you are right i want to write a web server. but the thing is that i dont know the exact code how to send the html file to the browser.  Here is the code that i used before to connect to a client. But show me where should i implement this html file things code.

#define PORT 3550  
main()
{
 
  int fd, fd2;

  struct sockaddr_in server;
  struct sockaddr_in client;

  int sin_size;


  if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ){  /* calls socket() */
    printf("socket() errorn");
    exit(-1);
  }

  server.sin_family = AF_INET;        
  server.sin_port = htons(PORT);  
  server.sin_addr.s_addr = INADDR_ANY;  */  
  bzero(&(server.sin_zero),8);
 
  if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){
      printf("bind() errorn");
      exit(-1);
  }    

  if(listen(fd,BACKLOG) == -1){        printf("listen() errorn");
      exit(-1);
  }

while(1){
  sin_size=sizeof(struct sockaddr_in);
  if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1){
    printf("accept() errorn");
    exit(-1);
  }
 
  printf("You got a connection from %sn",inet_ntoa(client.sin_addr) );
 
  send(fd2,"Welcome to my server.n",22,0);  
  close(fd2);}
}
0
 
sunnycoderCommented:
>send(fd2,"Welcome to my server.n",22,0);

here you should be reading from html file and sending what you read
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
pritam123456Author Commented:
and if i Put the code like this

send(fd2,index.html,22,0);  

will this work. and is this the only thing that i have to change in the whole code????
0
 
sunnycoderCommented:
No ... Read the file .. fread,fgets etc

Are you familiar with file I/O ?
0
 
pritam123456Author Commented:
no am not quite familiar with this. can you help me with that. i already have a html how would i read it and send it to the browser??
0
 
sunnycoderCommented:
Is this just an academic project or do you intend to write a real web server ?
0
 
sunnycoderCommented:
some good theory about streams and examples for reading/writing files
http://www.cs.cf.ac.uk/Dave/C/node18.html#SECTION001800000000000000000

refer to man pages of
fopen
fread
fgets
fscanf
fwrite
fputs
fprintf
fclose
0
 
pritam123456Author Commented:
its just an accademic project. This input and output appear to be complicated. how should i start it.
0
 
sunnycoderCommented:
just read the tutorial and write a couple of practice programs
0
 
keteracelCommented:
hey sunny, he's my hero: http://www.ecst.csuchico.edu/~beej/guide/net/html/

I've even mirror'ed it, if you're in the uk this should be quicker:

http://www.keteracel.com/comframe.php?link=http://www.keteracel.com/community/beej/
0
 
sunnycoderCommented:
interesting keteracel ... I learnt my entire socket programing from this tutorial ... never read a book ;o) ... I was quite impressed with it the first time ... Tutorials of this quality are a rarity
0
 
pritam123456Author Commented:
the IO with Unix socket using C is so confusing. can anyone gave me a sample code of how to read from a text file or html file using C Coding??
0
 
pritam123456Author Commented:
i have been able to modify some code. its can read the html file. but when i am using my web browser to connect to the server its still not working. it is not sending the index.html file. can some find the error for me please?


#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <curses.h>
#include <sys/time.h>
#include <netdb.h>

#define MAXLINE 1000
#define SA struct sockaddr

#define DOCUMENT "index.html"

void
sigchld_handler(int s)
{
      while (wait(NULL) > 0);
}
void
send_doc(int connfd)
{
      FILE *fp;
      char output[1000];
      int len;
      
      if((fp = fopen(DOCUMENT, "r")) == NULL) {
            printf("Cannot open file.\n");
            exit(1);
      }
            
      while(!feof(fp)) {
            fgets(output, 999, fp);
            len = strlen(output);
            if (sendall(connfd, output, &len) == -1) {
                  perror("sendall");
                  printf("We only sent %d bytes because of the error!\n", len);
            }
      }

}
int
sendall(int s, char *buf, int *len)
{
      int             total = 0;
      
      int             bytesleft = *len;
      
      int             n;

      while (total < *len) {
            n = send(s, buf + total, bytesleft, 0);
            if (n == -1) {
                  break;
            }
            total += n;
            bytesleft -= n;
      }
      *len = total;
      
            return n == -1 ? -1 : 0;
      
}

int
main(void)
{
      int             listenfd, connfd;
      pid_t           childpid;
      socklen_t       clilen;
      struct sockaddr_in cliaddr, servaddr;
      struct sigaction sa;
      int             len, yes = 1, sin_size, nbytes;

      char            data[1000];

      if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
      }
      if ((connfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
      }
      if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
      }
      bzero(&servaddr, sizeof(servaddr));
      servaddr.sin_family = AF_INET;
      servaddr.sin_addr.s_addr = INADDR_ANY;
      servaddr.sin_port = htons(8080);

      if (bind(listenfd, (struct sockaddr *) & servaddr, sizeof(struct sockaddr)) == -1) {
            perror("bind");
            exit(1);
      }
      if (listen(listenfd, 10) == -1) {
            perror("listen");
            exit(1);
      }
      sa.sa_handler = sigchld_handler;
      
            sigemptyset(&sa.sa_mask);
      sa.sa_flags = SA_RESTART;
      if (sigaction(SIGCHLD, &sa, NULL) == -1) {
            perror("sigaction");
            exit(1);
      }
      for (;;) {
            clilen = sizeof(cliaddr);
            if ((connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) == -1) {
                  perror("accept");
                  exit(1);
            }
            printf("server: got connection from %s\n", inet_ntoa(cliaddr.sin_addr));
            if ((childpid = fork()) == 0) {
                  close(listenfd);
                  send_doc(connfd);
                  sleep(10);
                  exit(0);
                  
            }
            close(connfd);
      }
}
0
 
sunnycoderCommented:
any error messages ? some diagnostic symptoms ?
0
 
pritam123456Author Commented:
it is not working with the internet explorer. when i used another console application as client, i can get all the html coding but with internet explorer it is not working.
0
 
sunnycoderCommented:
run the server on port 80 or tell internet explorer explicitly which port to connect to

http://my_server_ip:my_port
0
 
pritam123456Author Commented:
i have been trying it atleast 10 times with different port number including the port 80 but it is still not working.
0
 
sunnycoderCommented:
run the code exactly as above ...

from IE

http://my_server:8080/
0
 
pritam123456Author Commented:
i have been running it exactly as above but it is not working have u tried it???
0
 
pritam123456Author Commented:
can anyone help me. I have tried the above code its working perfectly. it is displaying index.html as default which is in the root directory. now i want to modify the code so that it can display any requested page stored in the root folder.? how will i do that??
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 10
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now