/* cludp1.c - Client using datagram service on sockets 
              It has two command line parameters: a host name, and a 
	      port number.
              It sends the current time to the server, waits for
	      and prints the reply, and repeats after waiting
	      for 30 seconds.
*/

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


main(argc, argv)
     int argc;
     char *argv[];
{
  int sock;                /* file descriptor for socket */
  long tm;                 /* time */
  struct sockaddr_in name; /* Address of the server */
  struct hostent *hp;
  char data[2048];
  
  /* create a socket */
  sock = socket(AF_INET, SOCK_DGRAM, 0);
  if(sock < 0) {
    perror("Opening datagram socket");
    exit(1);
  }

  /* Host and port come from input arguments */
  /* Fill in the server's UDP address */
  hp = gethostbyname(argv[1]);
  if(hp == 0) {
    fprintf(stderr, " %s: unknown host",argv[1]);
    printf("Error h_errno %d\n", h_errno);
    exit(2);
  }
  bcopy((char *)hp->h_addr, (char *)&name.sin_addr, hp->h_length);
  name.sin_family = AF_INET;
  name.sin_port = htons(atoi(argv[2]));
  while (1) {
    /* send the message */
    time(&tm);
    printf("At Client: Current time is %s\n", ctime(&tm));
    strcpy(data, ctime(&tm));
    if(sendto(sock, data, strlen(data) * sizeof(char), 0,
	      (struct sockaddr *)&name, sizeof(name)) < 0)
      perror("Sending datagram message");
    
    /* Wait for the reply */	
    if(read(sock, data,(1024 * 2)) < 0) {
      perror("Error receving data from server");
      exit(1);
    }
    printf("Data from server %s\n", data);
    sleep(30);
  }
  close(sock);
  exit(0);
}

