Guest User

T_X

a guest
Jun 12th, 2013
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. /**
  2.  * CC0 - Linus Lüssing
  3.  */
  4.  
  5. #include <stdio.h>      // for fprintf()
  6. #include <net/if.h>     // for if_nametoindex()
  7. #include <stdlib.h>     // for atoi() and exit()
  8. #include <arpa/inet.h>  // for sockaddr_in and inet_addr()
  9. #include <string.h>     // for memset()
  10.  
  11. int create_client_multirecv_socket(char *multicastIP, unsigned int multicastPort, char *interface)
  12. {
  13.     int sd;                 // Socket descriptor
  14.     struct sockaddr_in6 multicastAddr;  // Multicast addresse structure
  15.     struct ipv6_mreq multicastRequest;  // Multicast address join structure
  16.  
  17.     // Construct bind structure
  18.     memset(&multicastAddr, 0, sizeof(multicastAddr));   // Zero out structure
  19.     multicastAddr.sin6_family = AF_INET6;       // Internet address family
  20.     multicastAddr.sin6_addr = in6addr_any;      // Any incoming interface
  21.     multicastAddr.sin6_port = htons(multicastPort); // Multicast port
  22.  
  23.     // Create a best-effort datagram socket using UDP
  24.     if((sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
  25.         perror("socket() failed");
  26.         return -1;
  27.     }
  28.     // Bind to the multicast port
  29.     if(bind(sd, (struct sockaddr *) &multicastAddr, sizeof(multicastAddr)) < 0) {
  30.         perror("bind() failed");
  31.         return -1;
  32.     }
  33.     // Specify the multicast group
  34.     if(!inet_pton(AF_INET6, multicastIP, &multicastRequest.ipv6mr_multiaddr)) {
  35.         fprintf(stderr, "Invalid IP-address: %s", multicastIP);
  36.         return -1;
  37.     }
  38.     // Accept multicast from specified interface
  39.     multicastRequest.ipv6mr_interface = if_nametoindex(interface);
  40.  
  41.     // Join the multicast address
  42.     if(setsockopt(sd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (void *) &multicastRequest,
  43.         sizeof(multicastRequest)) < 0) {
  44.         perror("setsockopt() failed");
  45.         return -1;
  46.     }
  47.  
  48.     return sd;
  49. }
  50.  
  51.  
  52.  
  53. int main(int argc, char *argv[])
  54. {
  55.     int sd;
  56.  
  57.     if (argc < 3) {
  58.         perror("Not enough command line arguments (must be 2, multicast group and interface");
  59.         exit(1);
  60.     }
  61.  
  62.     sd = create_client_multirecv_socket(argv[2], 12999, argv[1]);
  63.     if(sd < 0) {
  64.         perror("create_client_multirecv_socket failed");
  65.         exit(1);
  66.     }
  67.  
  68.     while(1)
  69.         sleep(100);
  70.  
  71.     close(sd);
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment