Complete Communications Engineering

This can be done in just two steps: create a UDP socket and use the sendto function with a multicast address.  The UDP socket is created with the socket function.  Multicast addresses are defined by the IP protocol.  For IPv4, any address that begins with the bit sequence ‘1110’ is a multicast address.  This includes all addresses in the range [224.0.0.0 – 239.255.255.255].  Many of these addresses are registered with IANA for specific uses.  For most applications, the local scope multicast addresses defined in RFC2365 (239.255.0.0/16) are good to use.  The following C code demonstrates sending a multicast packet:

server.c

#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 group;

    char buf[128];

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

 

    /* Fill out the multicast address for sending messages */

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

    group.sin_family = AF_INET;

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

    group.sin_port = htons(MULTICAST_PORT);

 

    /* Send a message to the multicast address */

    sprintf(buf, “Hello from multicast server”);

    sendto(s, buf, strlen(buf), 0, (struct sockaddr *)&group,

           sizeof(group));

 

    printf(“Multicast message was sent.\n”);

 

    return 0;

}

The program first declares some variables: a socket address to hold the multicast address to send to, a buffer to hold the message to send, and a handle for the UDP socket.  The socket handle is initialized using the socket function.  Next, the multicast address is filled out.  This requires both an address and a port.  After this the buffer is filled with a message to send, and the sendto function is used to send it.