/***************************************************************************************
	Example of server code - receive a string and capitalize it and send it back
****************************************************************************************/
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>

int 	sd, sd2;						// socket descriptor ID

int main(int argc, char *argv[])
{
	struct hostent *ptrh;					// pointer used by gethostbyname 
	struct sockaddr_in sad,cad;				// structure to hold server's address and client's address	
	int portnumber = 9001;					// portnumber 
	char msg[1028];							// message
	int i,j,n;

	memset((char *)&sad, 0, sizeof(sad)); 			// clear out sad
	sad.sin_family = AF_INET;
	sad.sin_addr.s_addr = INADDR_ANY;

	if (portnumber > 0 && portnumber < 65535) 
		sad.sin_port = htons((u_short)portnumber);
	else {
		fprintf(stderr, "Error - Invalid port number: %s \n",argv[1]);
		exit(1);		
	}

	// **** MAKE THE SOCKET ****
	// create a socket and get a socket descriptor
	sd = socket(PF_INET, SOCK_STREAM, 0);
	if (sd < 0) {	
		fprintf(stderr, "Error - Socket creation failed\n");
		exit(1);
		}
	// bind a local address to the socket
	if (bind(sd,(struct sockaddr *)&sad, sizeof(sad)) < 0) {	
		fprintf(stderr, "Error - Bind failed\n");
		exit(1);
	}
	// listen and wait for a connection from a client
	if (listen(sd, 10) < 0) {
		fprintf(stderr, "Error - Listen failed\n");
		exit(1);	
	}

	//main loop - accept and process requests
	while (1) {
       // 	pthread_t childid;  (here's what you would need to setup a thread to handle each request)
		int addr_len = sizeof(sad);
		if ((sd2 = accept(sd, (struct sockaddr *)&sad, &addr_len)) < 0) {	// wait for and accept new request
			fprintf(stderr, "Error - Accept failed\n");
			exit(1);	
		}
		printf("%d\n",sd2);
			// Here's where you would want to send off a thread to work with this socket
		// get the message
		n = recv(sd2,msg,sizeof(msg),0);
		printf("RECEIVED FROM CLIENT: %s\n",msg);
		for (i=0;i<n;i++)
		{
			//capitalize every letter in the message
			msg[i] = toupper(msg[i]);
		}
		//put the message back into the socket
		write(sd2,msg,n);
	}

}






