Tfe

Ongi etorri tfe-ren webgunera...

Old stuff/ecole_etude_fac_de_pau/licence_3/systeme-distribues/tp2/client.c

(Deskargatu)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

#define TAILLEBUF 20

int main(int argc, char** argv){

  int default_port = 4000;
  char* default_serv = "localhost";
  int i;
  if (argc>2) { 
    default_port = 0;
    for (i=0; i<strlen(argv[1]);i++)
      {
	default_port = default_port*10 + (int)argv[1][i] - 48;
      }
   default_serv = argv[2]; 
  }

  printf("au final port = %d et serv: %s \n", default_port, default_serv);


  struct hostent *serveur_host;
  static struct sockaddr_in addr_serveur;
  socklen_t lg;
  int sock;

  FILE* f;
  char *msg="bonjour";
  char reponse[TAILLEBUF];
  int nb_octets;
  sock=socket(AF_INET,SOCK_STREAM,0);
  if (sock==-1){
    perror("erreur creation socket");
    exit(1);
  }
  serveur_host=gethostbyname(default_serv);
  if (serveur_host==NULL){
    perror("erreur adresse serveur");
    exit(1);
  }
  bzero((char*)&addr_serveur,sizeof(addr_serveur));
  addr_serveur.sin_family=AF_INET;
  addr_serveur.sin_port=htons(default_port);
  memcpy(&addr_serveur.sin_addr.s_addr,serveur_host->h_addr,serveur_host->h_length);


  if (connect(sock,  (struct sockaddr*)&addr_serveur, sizeof(struct sockaddr_in)) == -1) {
    perror("erreur conect"); 
    exit(-1);
  }
  nb_octets = write(sock, msg, strlen(msg)+1);
  printf("envoie de %s\n",msg);

  nb_octets = 1;
  
  f = fopen("prout.txt","w");
  while (nb_octets != 0)
    {
      bzero(reponse,TAILLEBUF);
     nb_octets= read(sock, reponse, TAILLEBUF-1);
  printf("%s",reponse);
    }

  //  close(sock);
}