/* server.c - code for example server program that uses UDP */

#include <stdio.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

main(argc, argv)
     int     argc;
     char    *argv[];
{
  struct  sockaddr_in sad; /* structure to hold server's address  */
  int     port;            /* protocol port number                */
  
  struct  sockaddr_in cad; /* structure to hold client's address  */
  int     alen;            /* length of address                   */
  
  int     serverSocket;     /* socket descriptors  */
  
  char    clientSentence[128]; 
  char    capitalizedSentence[128]; 
  char    buff[128];
  int     i, n;
  
  /* Check command-line argument for protocol port and extract   */
  /* port number if one is specified. Otherwise, give error      */
  if (argc > 1) {                /* if argument specified        */
    port = atoi(argv[1]);        /* convert argument to binary   */
  } else { 
    fprintf(stderr,"Usage: %s port-number\n",argv[0]);
    exit(1);
  }
  
  /* Create a socket */

  serverSocket = socket(PF_INET, SOCK_DGRAM, 0); /* CREATE SOCKET */
  if (serverSocket < 0) {
    fprintf(stderr, "socket creation failed\n");
    exit(1);
  }
  
  /* Bind a local address to the socket */
  
  memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure   */
  sad.sin_family = AF_INET;           /* set family to Internet     */
  sad.sin_addr.s_addr = INADDR_ANY;   /* set the local IP address   */
  sad.sin_port = htons((u_short)port);/* set the port number        */ 
  
  if (bind(serverSocket, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
    fprintf(stderr,"bind failed\n");
    exit(1);
  }
  
  /* Main server loop - accept and handle requests */
  
  while (1) {
    
    /* Get the sentence from the client  and the address of the client*/
    
    clientSentence[0]='\0';
    
    alen = sizeof(struct sockaddr);
    n=recvfrom(serverSocket,buff,sizeof(buff),0,
	       (struct sockaddr *) &cad, &alen);
    strncat(clientSentence,buff,n);
    clientSentence[n] ='\0';
    
    printf("Server received :%s \n", clientSentence);

    
    /* Capitalize the sentence or whatever is received */
    
    for(i=0; i <= strlen(clientSentence); i++){
      if((clientSentence[i] >= 'a') && (clientSentence[i] <= 'z'))
	capitalizedSentence[i] = clientSentence[i] + ('A' - 'a');
      else
	capitalizedSentence[i] = clientSentence[i];
    }
    
    /* send it to the client */
    
    n=sendto(serverSocket, capitalizedSentence, strlen(capitalizedSentence)+1,0,
	     (struct sockaddr *) &cad, alen );
    printf("Server sent %d bytes to client\n",n);
  }
} 





