Complete Communications Engineering

Multicast packets can be received by UDP sockets that are bound to an unspecified address (INADDR_ANY).  In addition, the receiving computer must subscribe to the multicast address using the IGMP protocol.  The IGMP protocol is used by routers on the network to decide which interfaces multicast packets should be forwarded to.  Binding is done using the function bind, and subscribing is done using the setsockopt function with the option name IP_ADD_MEMBERSHIP.  The following C code demonstrates receiving a multicast packet:

#include <stdio.h>

#include <string.h>

#include <unistd.h>

#include <netinet/ip.h>

#include <arpa/inet.h>

 

#define MULTICAST_PORT 9002

#define MULTICAST_ADDR “239.255.42.1”

 

int main (int argc, char *argv[])

{

    struct sockaddr_in local;

    struct ip_mreq group;

    char buf[128];

    const char *local_addr = argv[1];

    int s = socket(AF_INET, SOCK_DGRAM, 0);

 

    /* Bind the UDP socket to the multicast port */

    memset(&local, 0, sizeof(local));

    local.sin_family = AF_INET;

    local.sin_port = htons(MULTICAST_PORT);

    bind(s, (struct sockaddr *)&local, sizeof(local));

 

    /* Request membership in the multicast group */

    memset(&group, 0, sizeof(group));

    inet_pton(AF_INET, MULTICAST_ADDR, &group.imr_multiaddr);

    inet_pton(AF_INET, local_addr, &group.imr_interface);

    setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&group,

               sizeof(group));

 

    printf(“Listening for multicast message…\n”);

 

    /* Read the multicast message */

    read(s, buf, sizeof(buf));

    printf(“Read multicast message: ‘%s’\n”, buf);

 

    return 0;

}

The code first defines a few variables.  It defines a socket address where the UDP socket will be bound, a group structure for subscribing to the multicast address, a buffer to store the received message, a local address string telling which local network interface will receive the multicast packets, and a handle for the socket.  The local address is initialized from the command line, and the socket is initialized using the socket function.  Next, the bind_addr variable is filled out with the multicast port.  The address is left as all zeros, which is the same as INADDR_ANY, and then it is used in the bind function.  After that the group structure is filled out with both the multicast address and the local address and used in the setsockopt function to request membership.  Once all of this is done, multicast data can be read from the socket.