/**********************************************************************

              CLIENT-SERVER su socket di tipo STREAM


    	                C   L  I  E  N  T

**********************************************************************/

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



#define BYTES_NR 1024

char	buf[BYTES_NR];




/************
Utilizzo:
client servername porta nomefile
************/

main(argc,argv)
int	argc;char *argv[];
{
int	i,s,fd,sock,rval,rval2,filesize;
struct 	sockaddr_in 	server;
struct	hostent	*hp,*gethostbyname();



if(argc != 4)
  {
    fprintf(stderr,"Uso: %s servername port filename\n\n",argv[0]);
    exit(-1);
  }

/* Crea una  socket di tipo STREAM per il dominio TCP/IP */
sock=	socket(AF_INET,SOCK_STREAM,0);

if(sock<0)
	{
	perror("opening stream socket");
	exit(1);
	}


/* Ottiene l'indirizzo del server */


server.sin_family=	AF_INET;

hp=	gethostbyname(argv[1]);

if(hp==0)
	{
	fprintf(stderr,"%s: unknown host",argv[1]);
	exit(2);
	}


 memcpy( (char *)&server.sin_addr, (char *)hp->h_addr ,hp->h_length);
 
 
 /* La porta e' sulla linea di comando */
 server.sin_port= htons(atoi(argv[2]));

 /* Tenta di realizzare la connessione */
 printf("Connecting to the server %s...\n",argv[1]);
 if(connect(sock,(struct sockaddr *)&server,sizeof server) <0)
   {
     perror("connecting stream socket");
     exit(-1);
   }
 
 printf("Connected to the server.\n");
 
 
 strcpy(buf,argv[3]);
 if(   write(sock,buf, strlen(buf)+1) <0)
   {
     perror("connecting stream socket");
     exit(-2);
   }
 
 /* Ricezione dal server */
 if((rval = read(sock,&filesize,sizeof filesize))<0)
   {
     perror("reading server answer");
     exit(-3);
   }
 
 
 printf("Server tells us file %s is %d bytes long \n",argv[3],filesize);
 
 exit(0);
}


