Tfe

Ongi etorri tfe-ren webgunera...

Old stuff/ecole_etude_fac_de_pau/licence_3/systeme-distribues/tp3/serveur.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>
#include       <string.h>


#define TAILLEBUF 20
int main(int argc, char** argv) {

  int default_port = 4000;
  int i;
  if (argc>1) { 
    default_port = 0;
    for (i=0; i<strlen(argv[1]);i++)
      {
	default_port = default_port*10 + (int)argv[1][i] - 48;
      }
    //    default_port = argv[1]; 
  }
  printf("au final port = %d\n",default_port);

static struct sockaddr_in addr_client;
static struct sockaddr_in addr_serveur;
struct hostent *host_client;
socklen_t lg;
int sock,socket_ecoute,socket_service;

char reponse[10];
char buffer[TAILLEBUF];
char *chaine;
int nb_octets;

socket_ecoute = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {      perror("erreur création socket");      exit(1); }

bzero((char*)&addr_serveur, sizeof(addr_serveur));

addr_serveur.sin_family = AF_INET;
addr_serveur.sin_port = htons(default_port);
addr_serveur.sin_addr.s_addr=htonl(INADDR_ANY);

if( bind(socket_ecoute, (struct sockaddr*)&addr_serveur,sizeof(addr_serveur))== -1 ) {
    perror("erreur bind");          exit(1); }

lg = sizeof(struct sockaddr_in);

 if (listen(socket_ecoute, 5) == -1) {
   perror("erreur listen");
   exit(-1);
 }

  socket_service = accept(socket_ecoute, (struct sockaddr*)&addr_client, &lg);
 if (socket_service == -1) {
   perror("socket service");
   exit(-1);
 }

 nb_octets = read(socket_service, buffer, TAILLEBUF);
 chaine = (char*)malloc(nb_octets * sizeof(char));
 memcpy(chaine, buffer, nb_octets);
 printf("recue message: %s\n",chaine);

 FILE* f= fopen("serveur.c","r");
 if (f== NULL) { perror("erreur fopen"); exit(-1); }
 printf("fichier ouvert");

 while(! feof(f))
   {
     bzero(reponse,20);
     lg=fread(reponse,1,20,f);
     printf("%s",reponse);
     write(socket_service,reponse, lg);
   }
 fclose(f);
 close(socket_service);
 close(socket_ecoute);



}