/* client3.c by Leo Wolpert, adapted from Beej's
   client.c (http://www.ecst.csuchico.edu/~beej/guide/net/)
   This client recieves messages until the server sends the
   disconnect command.

   Usage at command line: client3 hostname
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORT 6996    /* the port the client will be connecting to */

#define MAXDATASIZE 100 /* max number of bytes the message recieved can have */

int main(int argc, char *argv[])
{
    int sockfd, numbytes, a, count=0;  
    char buf[MAXDATASIZE];  /* String into which recieved messages will go */
    struct hostent *he;
    struct sockaddr_in their_addr; /* connector's address information */
    printf("Starting client program.\n"  );

    if (argc != 2)
    /* Check command line */
    {
        fprintf(stderr,"You forgot to enter the hostname of the server.\n   usage: client3 hostname\n");
        exit(1);
    }

    if ((he=gethostbyname(argv[1])) == NULL) 
    /* get the host info */
    {
        perror("gethostbyname");
        exit(1);
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 
    /* Create socket file descriptor */
    {
        perror("socket");
        exit(1);
    }

    their_addr.sin_family = AF_INET;         /* host byte order */
    their_addr.sin_port = htons(PORT);       /* short, network byte order */
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    bzero(&(their_addr.sin_zero), 8);        /* zero the rest of the struct */

    if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) 
    /* Connect to server */
    {
        perror("connect");
        exit(1);
    }
    printf("Waiting for messages from the server.\n");
    while(sockfd)
    /* While the file descriptor exists */
    {
       count=count+1; /* Increment counter (to show message number) */
       if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) 
       /* Recieve data from server */
       {
          perror("recv");
          exit(1);
       }
     
       buf[numbytes] = '\0';

       if(buf[0]=='/' && buf[1]=='Q')
       /* Check for quit */
       {
          printf("\n\nSERVER IS CALLING IT QUITS: GOODBYE\n\n");
          exit(0);
       }
       printf("%d. %s \n", count, buf); /* Print message */
        
    }
    close(sockfd);

    return 0;
}

