I am using java.nio.channels.DatagramChannel to send and receive UDP multicast messages. The box, my program is running on can have multiple network interfaces.
I can specify network interface manually using socket option for outgoing datagrams:
NetworkInterface ni = NetworkInterface.getByName("eth0");
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
and passing network interface to join method for incomming datagrams:
MembershipKey key = channel.join(group, ni);
But I'd like my app to use the default interface based on routing tables. For outgoing data it is easy. I should not to specify IP_MULTICAST_IF or pass null as network interface. Java doc says the following:
"The initial/default value of this socket option may be null to indicate that outgoing interface will be selected by the operating system, typically based on the network routing tables."
But what is about incoming data. The method "join" always requires the network interface to be specified, and it does not allows me to pass null.
Ideally I'd like to join the multicast groups on exactly the same interface that is used for this multicast group for outgoing datagrams by default.
Is there any way to do it?
I am using Java 8 and Linux OS.
There isn't any explicit support in the DatagramChannel API for joining a multicast group on an interface chosen by the system but you can workaround it by using MulticastSocket::getNetworkInterface to obtain the placeholder NetworkInterface. So this should do what you want:
NetworkInterface ni;
try (MulticastSocket s = new MulticastSocket()) {
ni = s.getNetworkInterface();
}
MembershipKey key = channel.group(join, ni);
The MulticastSocket is created solely to call the getNetworkInterface.