socketsroutermulticastloopback

Loopback in multicast


This question is about sending and receiving multicasts inside the same host, while simultaneously sending it to other hosts.

Even after hours of googling, I have not been able to sort out, how multicast datagrams are routed within the same host..!

Here comes a detailed description of the problem:

Linux box "A" is cable-connected to a switch/router (let's call the switch/router as "R").

In linux box A, I have a process (A0) that sends UDP packets to multicast address "224.0.0.0", port 5000.

Likewise, in the same box A, I have two processes (A1 and A2), both connecting to 224.0.0.0, port 5000 and consuming UDP packets.

Now, how does the kernel in box A manage the routing?

So, A0 sends a datagram which is consumed by A1 and A2. Does such a datagram do a round-trip A --> R --> A ?

.. or is the kernel routing in "A" smart enough to avoid this unnecessary round-trip? (i.e. datagram is sent by A0 and consumed right away by A1 and A2, never leaving A).

Of course, one can ensure that multicast datagram never leave A, by creating and enforcing a loopback device for multicast:

sudo ifconfig lo multicast
sudo route add -net 224.0.0.0 netmask 240.0.0.0 dev lo

But now, if I want to consume the UDP datagram simultaneously in another linux box, say, "B", there is no way they arrive there.

So, ideally, (1) datagram consumed in A should never leave A (i.e. no round trip A --> R --> A), while (2) datagram consumed in B should go normally as A --> R --> B. I'd like to achieve these two things simultaneously.

Any way to achieve this, for example, with the "route" command ?

Sockets is processes A1 and A2 have the following flags set:

SO_REUSEADDR
SO_REUSEPORT

While I have checked that process A0 (the one that sends multicast datagram) has the following flag on:

IP_MULTICAST_LOOP

Solution

  • Looping back to local processes (local sockets) should work without adding a multicast route to lo. Just make sure you have a useful route set to some external interface. The packets will still be routed internally. (Linux does a lot of routing behind the scenes.)

    You need IP_MULTICAST_LOOP, this looks good.

    Did you properly join the multicast group in all processes? IP_ADD_MEMBERSHIP? Without this you get all kinds of bogus behavior.

    You can look at the local routing table to see what Linux does locally to packets. It is usually far from trivial:

    sudo ip route show table local

    You can also look at the current multicast group memberships:

    netstat -g

    Does the output and the ref counts make sense in your case?