/* svudp1.c  - Server using datagram service with sockets. In a loop
               it prints out the message it receives from a client
	       and sends back the current time.
*/

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

#define MAXBUF 2 * 1024


main(argc, argv)
   int argc;
   char *argv[];
{
  int sock;  /* file descriptor into UDP */
  struct sockaddr_in name; /* the address of this service */
  int length; /* length of address */
  char buf[MAXBUF]; /* buffer to hold datagram */
  struct sockaddr_in client_addr; /* the address of the client */ 
  long tm; /*time*/
	
  /* create a socket */
  sock = socket(AF_INET, SOCK_DGRAM, 0);
  if(sock < 0) {
    perror("Opening datagram socket");
    exit(1);
  }
  bzero((char *)&name, sizeof(name));
  name.sin_family = AF_INET;
  name.sin_addr.s_addr = INADDR_ANY;
  name.sin_port = 0;

  if(bind (sock, (struct sockaddr *)&name,sizeof(name)) < 0) {
    perror("Error binding datagram socket \n");
    exit(1);
  }

  /* print port number */
  length = sizeof(name);
  if (getsockname(sock, (struct sockaddr *)&name, &length) < 0) {
    perror("Error getting socketname \n");
    exit(1);
  }
  printf("Socket port #%d\n", ntohs(name.sin_port));
  
  length = sizeof(struct sockaddr);
  while(1) {
    if(recvfrom(sock, buf, MAXBUF, 0, &client_addr, &length) < 0) 
      perror("Couldn't read datagram"); 
    printf("From Client %s\n", buf);
    time(&tm);
    strcpy(buf, ctime(&tm));
    printf("Going to send to client %s\n", buf);
    if(sendto(sock, buf, MAXBUF, 0, &client_addr,
	      length) < 0) 
      perror("Couldn't send datagram"); 
  }
}




