echo_UDP_server.c
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <unistd.h>
00004 #include <netinet/in.h>
00005 #include <sys/types.h>
00006 #include <sys/socket.h>
00007 #include <string.h>
00008 #include <arpa/inet.h>
00009
00010 #define MAX_SIZE 256
00011 #define NUMPORT 6666 // Le port où les utilisateurs se connecteront
00012
00013 void error(char * msg);
00014 void traitement(int sockfd);
00015 int main()
00016 {
00017 int sockfd;
00018 struct sockaddr_in serv_addr;
00019
00020
00021 memset(&serv_addr, 0, sizeof(serv_addr));
00022 serv_addr.sin_family = AF_INET;
00023 serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
00024 serv_addr.sin_port = htons(NUMPORT);
00025
00026 if ( (sockfd = socket(PF_INET,SOCK_DGRAM,0)) < 0) error("[socket]");
00027
00028 if ( bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
00029 error("[bind]");
00030 while(1) {
00031 traitement(sockfd);
00032 }
00033 return EXIT_SUCCESS;
00034 }
00035
00036 void error(char * msg) {
00037 perror(msg);
00038 exit(EXIT_FAILURE);
00039 }
00040
00041 void traitement(int sockfd) {
00042 char requete[MAX_SIZE];
00043 struct sockaddr_in cl_addr;
00044 memset(&cl_addr, 0, sizeof(cl_addr));
00045 socklen_t len = sizeof(cl_addr);
00046
00047 ssize_t n1 = recvfrom(sockfd, requete, MAX_SIZE-1, 0,
00048 (struct sockaddr *)&cl_addr, &len);
00049 if (n1 < 0) error("[recvfrom]");
00050
00051 ssize_t n2 = sendto(sockfd, requete, n1, 0, (struct sockaddr *) &cl_addr, len);
00052 if ( n1 != n2 ) error("[sendto]");
00053 }