/* client.c - code d'un client TCP */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

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

#define PORT 12345
/*
 * Syntax:    client [ host [port] ]
 */
int main(int argc, char *argv[])
{
  struct hostent  *phe;
  struct protoent *ppe;
  struct sockaddr_in sin;
  int sc, port, n;
  char *host, buffer[1000];

  memset((char *)&sin,0,sizeof(sin));
  sin.sin_family = AF_INET;

  if (argc > 2) { port = atoi(argv[2]); }
  else          { port = PORT;          }
  if (port <= 0) {
    fprintf(stderr,"client: numero de port incorrect.\n");
    exit(1);
  }
  sin.sin_port = htons((u_short)port);

  if (argc > 1) { host = argv[1]; }
  else          { host = "localhost"; }

  if ((phe=gethostbyname(host))==NULL) {
    fprintf(stderr,"client: c'est quoi cette adresse (%s) ?\n", host);
    exit(1);
  }
  memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);

  if ((ppe=getprotobyname("tcp"))==NULL) {
    perror("client: getprotobyname(\"tcp\")");
    exit(1);
  }

  if ((sc=socket(PF_INET, SOCK_STREAM,ppe->p_proto)) < 0) {
    perror("client: socket()");
    exit(1);
  }

  if (connect(sc,(struct sockaddr *)&sin,sizeof(sin)) < 0) {
    perror("client: connect()");
    exit(1);
  }

  n = read(sc,buffer,sizeof(buffer));
  while (n > 0) {
    write(1,buffer,n);
    n = read(sc,buffer,sizeof(buffer));
  }

  close(sc);

  exit(0);
}
