#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 main(int argc, char *argv[])
{
	struct hostent *ptrh;			// pointer to host table entry 
	struct protoent *ptrp;			// pointer to protocol table entry
	struct sockaddr_in sad;			// Important field in address structure	
             					    //   sin_family	
                					//   sin_port
                                    //   sin_addr

	int sd;					// socket descriptor ID
	int n;					// number of characters to/from socket
	char buf[1028];			// buffer used to hold socket message
	int portnumber = 9001;			// portnumber to read/write
	
	// Catch the proper number of arguments	
	if (argc != 2)
	{
		printf("ERROR: Usage client string\n");
		exit(1);
	}
	
	memset ((char *)&sad, 0,sizeof(sad)); 	// clear out socket address area
	sad.sin_family = AF_INET;		// setup proper "family" type for address (in this case 

	sad.sin_port = htons((u_short)portnumber);  //make sure to put into network endian format
	ptrh = gethostbyname("localhost");
	if (((char *)ptrh) == NULL) {
		fprintf(stderr, "invalid host");
		exit(1);
		}
	memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);

	// get protocol 
	if (((int)(ptrp = getprotobyname("tcp"))) == 0) {
		fprintf(stderr, "cannot map \"tcp\" to protocol number");
		exit(1);
		}
	// create a socket and get socket descriptor
	sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
	if (sd < 0) {	
		fprintf(stderr, "socket creation failed\n");
		exit(1);
		}
	// **** CONNECT TO SERVER ****
	if (connect(sd, (struct sockaddr *)&sad, sizeof(sad))<0) {	
		fprintf(stderr, "connect failed\n");
		exit(1);
		}
	// write message to socket
	write(1,argv[1],strlen(argv[1]));
	write(1,"\n",1);
	write(sd,argv[1],strlen(argv[1]));
		// **** READ AND DISPLAY MESSAGES FROM SOCKET ****
	n = recv(sd,buf,sizeof(buf),0);
	write(1,"FROM SERVER: ",13);
	write(1,buf,n);
	write(1,"\n",1);
	
	// **** CLOSE CONNECTION ****
	close(sd);
	return(0);
}
