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
.
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:
% socat STDIO UDP4-DATAGRAM:239.101.1.68:8889,ip-add-membership=239.0.1.68:192.168.250.2
(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:
% netstat -gn
IPv6/IPv4 Group Memberships
Interface RefCnt Group
--------------- ------ ---------------------
lo 1 224.0.0.1
[...]
tun0 1 239.0.1.68
Finally, sniff your network interface:
# tshark -n -i tun0 -Y igmp
Running as user "root" and group "root". This could be dangerous.
Capturing on 'tun0'
Now, kill socat (pkill socat
, for instance).
You should see the following line, written by tshark:
7 2.197520 192.168.250.2 -> 224.0.0.22 IGMPv3 40 Membership Report / Leave group 239.0.1.68
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 of netstat -gn
.
Will multicast continue to be delivered to my network interface by the upstream router?
Not unless there are other group members in your host.
Is the OS (in my case Linux) smart enough to send the drop membership request for me when the socket is closed?
Yes. You don't need to worry about IP_DROP_MEMBERSHIP unless you want to change the groups dynamically on a socket, which is pretty rare: I've certainly never done it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With