Old stuff/ecole_etude_fac_de_pau/licence_3/systeme-distribues/tp1/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_local;
static struct sockaddr_in addr_client;
struct hostent *host_client;
socklen_t lg;
int sock;
char *reponse = "bien recu";
char buffer[TAILLEBUF];
char *chaine;
int nb_octets;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) { perror("erreur création socket"); exit(1); }
bzero(&addr_local, sizeof(struct sockaddr_in));
addr_local.sin_family = AF_INET;
addr_local.sin_port = htons(default_port);
addr_local.sin_addr.s_addr=htonl(INADDR_ANY);
if( bind(sock, (struct sockaddr*)&addr_local,sizeof(addr_local))== -1 ) {
perror("erreur bind"); exit(1); }
lg = sizeof(struct sockaddr_in);
nb_octets = recvfrom(sock, buffer, TAILLEBUF, 0,
(struct sockaddr *)&addr_client, &lg);
if (nb_octets == -1) { perror("erreur réception paquet"); exit(1);}
host_client = gethostbyaddr(&addr_client.sin_addr,sizeof(long), AF_INET);
if (host_client == NULL) { perror("erreur gethostbyaddr"); exit(1);}
chaine = (char *)malloc(nb_octets * sizeof(char));
memcpy(chaine, buffer, nb_octets);
printf("recu message %s de la part de %s sur le port %d\n", chaine, host_client->h_name,addr_client.sin_port);
nb_octets = sendto(sock, reponse, strlen(reponse)+1,
0,(struct sockaddr*)&addr_client, lg);
if (nb_octets == -1) { perror("erreur envoi réponse"); exit(1); }
}