/* * Simple ECHO udp server * (c)2013 JBY */ #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define PORT 5678 int main(int argc,char *argv[]) { struct sockaddr_in addr, from; int sock; char tampon[256]; socklen_t lg; int r; sock = socket(PF_INET,SOCK_DGRAM,0); // Protocol family if (sock==-1) { perror("socket: "); exit(1); } addr.sin_family = AF_INET; // Address family addr.sin_port = htons(PORT); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock,(struct sockaddr *)(&addr),sizeof(addr))==-1) { perror("bind: "); close(sock); exit(1); } while (1) { // Get a message lg = sizeof(from); r = recvfrom(sock,tampon,256,0,(struct sockaddr *)(&from),&lg); if (r==-1) { perror("recv:"); close(sock); exit(1); } // Print it tampon[r] = '\0'; printf("Recu : %s depuis la machine %08x et du port %d\n",tampon,ntohl(from.sin_addr.s_addr),ntohs(from.sin_port)); if (!strcmp(tampon,"quit")) break; // Send it back if (sendto(sock,tampon,256,0,(struct sockaddr *)(&from),lg)==-1) { perror("sendto:"); close(sock); exit(1); } printf("Renvoye : %s\n",tampon); } close(sock); return 0; }