/* This program creates a tcp client process in
   the internet domain.    The name of the 
   server machine and the port number are 
   passed to this program as arguments.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <strings.h> /* for bzero */
#include <unistd.h>
#include <stdlib.h> /* for atoi */

char *msg = "Hello from the client";

void error(char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
   int sock, n;
   unsigned short port;
   struct sockaddr_in server;
   struct hostent *hp;
   char buffer[1200];
   
   if (argc != 3) { 
         printf("Usage: %s server port\n", argv[0]);
         exit(1);
   }
   sock= socket(AF_INET, SOCK_STREAM, 0);
   if (sock < 0) error("Opening socket");

   server.sin_family = AF_INET;
   hp = gethostbyname(argv[1]);
   if (hp==NULL) error("Unknown host");
   bcopy((char *)hp->h_addr, 
         (char *)&server.sin_addr,
          hp->h_length);
   port = (unsigned short)atoi(argv[2]);
   server.sin_port = htons(port);
   if (connect(sock,
         (struct sockaddr *)&server, 
                     sizeof server) < 0)
             error("Connecting");
   n = write(sock, msg, strlen(msg));
   if (n < strlen(msg))
             error("Writing to socket");
     n=read(sock, buffer, 1024);
     if (n < 1) error("reading from socket");
     else{
        buffer[n]='\0';
        printf("The message from the server is %s\n",buffer);
     }
   close(sock);
   printf("Client terminating\n");
   return 0;
}
