All pastes #9597 Raw Edit

Multicast

public text v1 · immutable
#9597 ·published 2005-04-15 12:11 UTC
rendered paste body
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
#include <time.h> 
#include <stdio.h>

#define EXAMPLE_PORT 60123 
#define EXAMPLE_GROUP "224.0.0.250"

int main(int argc, char **argv) {
  struct sockaddr_in addr;  
  int addrlen, fd, cnt; 
  struct ip_mreq mreq; 
  char message[50];

  fd = socket(AF_INET, SOCK_DGRAM, 0); 
  if (fd < 0) { 
    perror("socket"); 
    exit(1); 
  }

  bzero(&addr, sizeof(addr)); 
  addr.sin_family = AF_INET; 
  addr.sin_addr.s_addr = htonl(INADDR_ANY); 
  addr.sin_port = htons(EXAMPLE_PORT); 
  addrlen = sizeof(addr);

  if (argc > 1) {   /* Send */ 
    addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP); 
    while (1) { 
      time_t t = time(0); 
      sprintf(message, "time is %-24.24s", ctime(&t)); 
      cnt = sendto(fd, message, sizeof(message), 0, 
		   (struct sockaddr *)&addr, addrlen); 
      if (cnt < 0) { 
	perror("sendto"); 
	exit(1); 
      } 
      sleep(5); 
    } 
  } else {    /* Receive */ 
    if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { 
      perror("bind"); 
      exit(1); 
    }

    mreq.imr_multiaddr.s_addr = inet_addr(EXAMPLE_GROUP); 
    mreq.imr_interface.s_addr = htonl(INADDR_ANY); 
    if (setsockopt(fd, IPPROT O_IP, IP_ADD_MEMBERSHIP, 
		   &mreq, sizeof(mreq)) < 0) { 
      perror("setsockopt mreq");
      exit(1); 
    }

    while (1) { 
      cnt = recvfrom(fd, message, sizeof(message), 0, 
		     (struct sockaddr *)&addr, &addrlen); 
      if (cnt <= 0) { 
	if (cnt == 0) { 
	  break; 
	} 
	perror("recvfrom"); 
	exit(1); 
      } 
      printf("%s: message = \"%s\"\n", 
	     inet_ntoa(addr.sin_addr), message); 
    } 
  } 
}