Programmation Avancée en C


socket_UDP_mcast_client.c

00001 #include <stdio.h> 
00002 #include <stdlib.h> 
00003 #include <unistd.h>
00004 #include <sys/socket.h>
00005 #include <arpa/inet.h>
00006 #define _POSIX_C_SOURCE 2
00007 #include <netdb.h>
00008 #include <string.h>
00009 #include "printtools.h"
00010 
00011 #define MAX_SIZE 256
00012 #define GROUP   "239.15.10.06"  // Format: 239.jj.mm.yy
00013 #define NUMPORT 6666
00014 
00015 void error(char * msg);
00016 int main() 
00017 {
00018     int sockfd = socket(PF_INET, SOCK_DGRAM, 0); // initialisation classique
00019     if (sockfd < 0) error("[socket]");
00020 
00021     struct sockaddr_in ip_mcast; // adresse de multicast du groupe (@IP+port)
00022     memset(&ip_mcast, 0, sizeof(ip_mcast));
00023     ip_mcast.sin_family      = AF_INET;
00024     if (inet_pton(AF_INET, GROUP, &(ip_mcast.sin_addr)) < 0) error("[inet_pton]");
00025     ip_mcast.sin_port        = htons(NUMPORT);    
00026  
00027     // Pour envoyer: il suffit d'envoyer à l'adresse du groupe
00028     char msg[] = "PING";
00029     ssize_t n = sendto(sockfd, msg, sizeof(msg), 0, 
00030                        (struct sockaddr *) &ip_mcast, sizeof(ip_mcast));
00031     if (n != sizeof(msg)) error("[sendto]");
00032 
00033     close(sockfd);
00034     return EXIT_SUCCESS;
00035 }
00036 
00037 void error(char * msg) {
00038     perror(msg);
00039     exit(EXIT_FAILURE);
00040 }