#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>

/* 
 * Creation: bana, 2007 november, computer networks
 * This program creates s socket and initiates a connection with the
 * socket given in the command line. Some data are sent over the
 * connection and then socket is closed, ending the connection.
 * The form of the command line is: streamwrite hostname portnumber
 */

main( argc, argv)
  int argc;
  char *argv[];
{
  int sock, rval;
  size_t length;
  struct sockaddr_in server;
  struct hostent *hp, *gethostbyname();
  
  struct
  {
    char host[128];
    short int port;
    short int fkod;
  } adat;

  strncpy(adat.host, argv[3], sizeof adat.host);
  adat.port = htons(atoi(argv[4]));
  adat.fkod = htons(atoi(argv[5]));
  
  char buff[1024];

  /* Create socket */
  
  sock = socket( AF_INET, SOCK_STREAM, 0 );
  if( sock == -1 ) {
	perror( "opening stream socket" );
	exit(1);
		    }

  /* Connect socket using name specified by command line. */

  server.sin_family = AF_INET;
  hp = gethostbyname( argv[1] );

 /*
  * gethostbyname returns a structure including the network address
  * of the specified host.
  */

  if ( hp == (struct hostent *) 0 ) {
	fprintf( stderr, "%s: unknown host \n", argv[1] );
	exit(2);
				     }

  memcpy( (void *) &server.sin_addr, (void *) hp->h_addr,
	  hp->h_length );
  server.sin_port = htons( atoi ( argv[2] ) );

  if( connect( sock, (struct sockaddr *) &server, sizeof server )
    == -1 ) {
	perror( "connecting stream socket" );
	exit(3);
	     }

  if( send( sock, &adat, sizeof adat, 0 ) == -1 )
	perror( "writing on stream socket" );

  if(( rval = recv( sock, buff, sizeof buff, 0 )) == -1 )
        perror( "reading stream socket" );
  else { 
	buff[rval] = '\0';
        printf( "-->%s\n", buff );
	}

  shutdown( sock, 1 );

  close( sock );
  
  exit(0);

}
