5. Stream Sockets

  1. Run the programs bellow. Make a clear description of the way this program works.

  2. What are the advantages of using sockets over named pipes?

  3. Rewrite the calculator program you wrote for the last laboratory assignment substituting the pipes for sockets .

    Note:

    Compile this programs in a Solaris system using the command:

    gcc foo.c -o foo -lsocket -lnsl

    Client Program

    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <stdio.h>
    
    #define DATA "1 2 3 TESTING ... "
    
    main (int argc, char* argv[])
    {
       int sock;
       struct sockaddr_in server;
       struct hostent *hp, *gethostbyname();
    
       sock = socket (AF_INET, SOCK_STREAM, 0);
       if (sock == -1) {
          perror ("Opening stream socket");
          exit (1);
       }
    
       hp = gethostbyname(argv[1]);
    
       memcpy ((char*)&server.sin_addr, (char*) hp->h_addr, hp->h_length);
    
       server.sin_family = AF_INET;
       server.sin_port = htons(atoi(argv[2]));
    
       if ( connect(sock, (struct sockaddr *)&server, sizeof server) == -1) {
          perror("Connecting stream socket");
          exit(1);
       }
    
       if (write(sock, DATA, sizeof DATA) == -1)
          perror("Writing data to stream socket");
    
       close (sock);
       exit (0);
    }

    Server Program

    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <stdio.h>
    
    #define TRUE 1
    
    main()
    {
       int sock, length;
       struct sockaddr_in server;
       int msgsock;
       char buf[1024];
       int rval;
    
       sock = socket (AF_INET, SOCK_STREAM, 0);
       if (sock==-1) {
          perror( "Opening stream socket");
          exit(1);
       }
    
       server.sin_family = AF_INET;
       server.sin_addr.s_addr = INADDR_ANY; 
       server.sin_port = 0;
       if (bind (sock, (struct sockaddr *)&server, sizeof(server)) == -1){
          perror("Binding stream socket");
          exit (1);
       }
       length = sizeof server;
       if (getsockname (sock, (struct sockaddr *)&server, &length) == -1){
          perror("Getting socket name");
          exit (1);
       }
       printf("Socket port # %d\n", ntohs(server.sin_port));
       /* Start accepting connections */
       listen( sock, 5);
       do {
          msgsock = accept( sock, (struct sockaddr *) 0, (int*) 0);
          if (msgsock==-1)
             perror("accept");
          else do {
             memset( buf, 0, sizeof buf);
             if (( rval= read( msgsock, buf, 1024)) == -1)
                perror("Reading data stream");
             if (rval == 0)
                printf("Ending connection\n");
             else
                printf( "-->%s\n", buf);
          } while (rval!=0);
          close(msgsock);
       } while (TRUE);
       exit(0);
    }