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;
  char *msg="bonjour";
  char buffer[TAILLEBUF];
  char *reponse;
  int nb_octets;
  sock=socket(AF_INET,SOCK_DGRAM,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(addr_serveur,sizeof(struct sockaddr_in));
  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);

  lg = sizeof(struct sockaddr_in);
  nb_octets = sendto(sock,msg,strlen(msg)+1,0,
		     (struct sockaddr*)&addr_serveur, lg);
  if (nb_octets == -1)
    {
      perror("Erreur envoie msg");
      exit(1);
    }
  printf("paquet envoyé , nboctets = %d\n",nb_octets);

  nb_octets = recvfrom(sock,buffer,TAILLEBUF,0,(struct sockaddr*)&addr_serveur,&lg);
  if (nb_octets == -1) { perror("erreur reception serveur"); exit(1); }
  reponse = (char*)malloc(nb_octets * sizeof(char));
  memcpy(reponse,buffer,nb_octets);
  printf("Recu du serveur: %s\n",reponse);

}