UDP: listening on the same port for two different multicast streams

I need to listen to 2 different multicast groups using the same port. Program Awill listen to 230.0.0.1and Program Bfrom 230.0.0.2. Both multicast groups use the same port 2000, and I do not control it.

When I run my programs, I get both multicast streams in each program and data packets broadcast to 230.0.0.1and 230.0.0.2. I suspect the problem is with the shared port. This is the code I use to subscribe to multicast:

if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0 ) {
  perror("socket");
  return -1;
}

if( setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0 ) {
  perror("setsockopt SO_REUSEADDR");
  return -1;
}

memset(&in_addr, 0, sizeof(in_addr));
in_addr.sin_family = AF_INET;
in_addr.sin_addr.s_addr = htonl(INADDR_ANY);
in_addr.sin_port = htons(2000);
if( bind(sd, (struct sockaddr*)&in_addr, sizeof(in_addr)) < 0 ) {
  perror("bind");
  return -1;
}

memset(&req, 0, sizeof(req));
inet_aton(intfc_ip, &req.imr_interface);
inet_aton("230.0.0.1", &req.imr_multiaddr);
if( setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &req, sizeof(req)) < 0 ) {
  perror("setsockopt IP_ADD_MEMBERSHIP");
  return -1;
}

recv()...

How can I filter a specific multicast group in each program?

+4
4

in_addr.sin_addr.s_addr = htonl(INADDR_ANY);

inet_aton(<your wanted IP address>, &in_addr.sin_addr.s_addr);

.

( getaddrinfo(), .)

+3

"connect" , . , TCP , UDP :

:

sockfd SOCK_DGRAM, addr - , , .

+3

, "recvfrom" , . IP-, . UDP-, , IP-, .

, , "recvmsg" recv recvfrom, IP-, .

1) setsockopt IP_PKTINFO, IP- , , , .

int enable = 1;
setsockopt(sock, IPPROTO_IP , IP_PKTINFO , &enable, sizeof(enable));

2) recvmsg recvfrom ( recv), , UDP. , "recvfromex", recvmsg recvfrom - , , IP- .

, ++ github , .

recvfromex

setsockopt ( "EnablePktInfo" , setsockopt IP_PKTINFO). IPV6 BSD.

+2

(from answer - C, Linux)

ip (7) manpage :

IP_MULTICAST_ALL ( ​​Linux 2.6.31)
                              , INADDR_ANY               . - ( - 1).                1,               , .                ,                (,               IP_ADD_MEMBERSHIP) .

You can then activate the filter to receive messages from the combined groups using:

int mc_all = 0;
if ((setsockopt(sock, IPPROTO_IP, IP_MULTICAST_ALL, (void*) &mc_all, sizeof(mc_all))) < 0) {
    perror("setsockopt() failed");
}
+1
source

All Articles