Solved

Socket programming

Posted on 2004-08-03
23
735 Views
Last Modified: 2008-02-01
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
Comment
Question by:pritam123456
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 10
23 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 50 total points
ID: 11703348
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
 

Author Comment

by:pritam123456
ID: 11703452
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11703496
>send(fd2,"Welcome to my server.n",22,0);

here you should be reading from html file and sending what you read
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

Author Comment

by:pritam123456
ID: 11703565
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11703606
No ... Read the file .. fread,fgets etc

Are you familiar with file I/O ?
0
 

Author Comment

by:pritam123456
ID: 11703625
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11703828
Is this just an academic project or do you intend to write a real web server ?
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11703843
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
 

Author Comment

by:pritam123456
ID: 11703910
its just an accademic project. This input and output appear to be complicated. how should i start it.
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11703935
just read the tutorial and write a couple of practice programs
0
 
LVL 9

Expert Comment

by:keteracel
ID: 11705419
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11705670
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
 

Author Comment

by:pritam123456
ID: 11723025
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
 

Author Comment

by:pritam123456
ID: 11724982
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11724993
any error messages ? some diagnostic symptoms ?
0
 

Author Comment

by:pritam123456
ID: 11725008
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11725019
run the server on port 80 or tell internet explorer explicitly which port to connect to

http://my_server_ip:my_port
0
 

Author Comment

by:pritam123456
ID: 11725036
i have been trying it atleast 10 times with different port number including the port 80 but it is still not working.
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11725046
run the code exactly as above ...

from IE

http://my_server:8080/
0
 

Author Comment

by:pritam123456
ID: 11725062
i have been running it exactly as above but it is not working have u tried it???
0
 

Author Comment

by:pritam123456
ID: 11742474
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Introduction to Processes

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question