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
typedef struct {
int op;
int a;
int b;
} op;
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);
}
pid_t pid;
while(1)
{
socket_service = accept(socket_ecoute, (struct sockaddr*)&addr_client, &lg);
if (socket_service == -1) {
perror("socket service");
exit(-1);
}
pid = fork();
if (pid == -1) { perror("error fork"); exit(-1); }
if (pid == 0) {
op o;
int resultat=1;
nb_octets = read(socket_service, &o, sizeof(op));
printf("Recu l operation %d %d %d \n",o.op,o.a,o.b);
switch(o.op)
{
case 1:
for(i=1;i<=o.a;i++) { resultat *= i; }
break;
case 2:
while (o.b>0){resultat *= o.a;
o.b--;}
break;
}
printf("Envoie de %d\n",resultat);
write(socket_service,&resultat, sizeof(int));
exit(1);
}
}
close(socket_service);
close(socket_ecoute);
}