/* 
   This file is part of Practical Distributed Processing
   Copyright (C) 2006-2007 Phillip J. Brooke and Richard F. Paige
*/

#include "constants.h"
#include "readloop.h"
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

/* 
   Open a socket, connect to port EXAMPLE_PORT of the given IP address
   (argument 1), and send text to the server..
*/

int main (int argc, char *argv[])
{
  int                s;
  struct hostent *   h;
  struct sockaddr_in a;
  
  printf("Client starting...\n");

  if ((s = socket(PF_INET, SOCK_DGRAM, 0)) >= 0)
    printf("The socket has been created\n");
  else
    {
      perror("Could not create socket");
      exit(EXIT_FAILURE);
    }

  a.sin_family = AF_INET;

  if (argc < 2)
    {
      printf("Need one argument: the name of the server!\n");
      exit(EXIT_FAILURE);
    }

  /* Given the string on the command line, turn it into a hostent
     structure. */
  if ((h = gethostbyname(argv[1])) == NULL)
    { 
      perror("Could not get host name");
      exit(EXIT_FAILURE);
    }
  printf("Hopefully, %s is the name of the server...\n", argv[1]);

  /* Copy the details we've just extracted and copy them into the
     address information.  Then set the port number. */
  memcpy(&a.sin_addr.s_addr, h->h_addr, h->h_length);
  a.sin_port = htons(EXAMPLE_PORT);

  /* Send stuff to the socket. */
  readloop2(s, (struct sockaddr *) &a, sizeof(a));

  /* Done?  close the socket. */
  if (close(s) != 0)
    perror("Warning: problem closing s");

  printf("Exiting.\n");
  exit(EXIT_SUCCESS);
}
