I'm working on some code which joins a multicast group using an IGMP join
struct ip_mreq mreq;
inet_pton(AF_INET, group, &mreq.imr_multiaddr.s_addr);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) < 0)
throw std::runtime_error(perror("setsockopt(IP_ADD_MEMBERSHIP)"));
When the application shuts down, it closes the socket
close(fd);
However, it doesn't perform an IP_DROP_MEMBERSHIP
.
- Will multicast continue to be delivered to my network interface by the upstream router?
- Is the OS (in my case Linux) smart enough to send the drop membership request for me when the socket is closed?
Yes, Linux maintains a reference count for each multicast group it has previously joined on a specific interface, and when you close the last file descriptor corresponding to a socket that asked for a specific group membership, Linux checks if the reference count to this group membership is null, and if this is the case, it will send a Membership Report with type 'Leave group', on the corresponding network interface.
Just do the following to check it by yourself:
Either use your program, or use
socat
to ask for a specific multicast group membership. For instance:(replace 192.168.250.2 by the address of one of your interfaces - note that in this example, the interface with this address is named
tun0
)Now, look at multicast groups membership on you Linux node:
Finally, sniff your network interface:
Now, kill socat (
pkill socat
, for instance). You should see the following line, written by tshark:Moreover, you can try to launch many instances of your program simultaneously, you will see that it's only when you kill the latest instance, that the
Leave group
message is sent. You also will see that the number of instances of your running programs is the number that appears in the output of the 2nd column ofnetstat -gn
.