Tfe

Ongi etorri tfe-ren webgunera...

Old stuff/ecole_etude_fac_de_pau/licence_3/systeme-distribues/tp3/testclient.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

typedef  struct
{
  int op;
  int a;
  int b;
} op;


int puissance(int a,int b)
{

  int default_port = 4000;
  char* default_serv = "localhost";
  int i;
 
  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);
  }
 

  op o;
  o.op = 1;
  o.a = a;
  o.b= b;
 nb_octets = write(sock, &o, sizeof(op));

printf("envoie du calcul %d %d %d\n",o.op,o.a,o.b);

  nb_octets = 1;
  
  int resultat;
  nb_octets= read(sock, &resultat, sizeof(int));
  return resultat;
}


int fact(int a)
{

  int default_port = 4000;
  char* default_serv = "localhost";
  int i;
 
  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);
  }
 

  op o;
  o.op = 2;
  o.a = a;
  
 nb_octets = write(sock, &o, sizeof(op));
  printf("envoie du calcul %d %d %d\n",o.op,o.a,o.b);

  nb_octets = 1;
  
  int resultat;
  nb_octets= read(sock, &resultat, sizeof(int));
  return resultat;
}




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

  printf("Resultat: %d\n",puissance(2,5));  

 printf("Resultat: %d\n",fact(5));  
 
}