bennyl
bennyl

Reputation: 2956

Join multicast group using DatagramChannel without specifying network interface

When using java's multicast socket I can join a multicast group without specifying a NetworkInterface using this code:

MulticastSocket sock = new MulticastSocket(PORT);
sock.joinGroup(ADDR);

If I want to use NIO on the other hand I can do:

DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
        .setOption(StandardSocketOptions.SO_REUSEADDR, true)
        .bind(new InetSocketAddress(PORT))
        .setOption(StandardSocketOptions.IP_MULTICAST_IF, IFC);

dc.join(ADDR, IFC);

where IFC is the NetworkInterface I am interested on. If I dont know the network interface in advance how can I join a group like with the MulticastSocket?

One solution that I found is using this code:

MulticastSocket msock = new MulticastSocket();
NetworkInterface ifc = msock.getNetworkInterface();
msock.close();
DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
        .setOption(StandardSocketOptions.SO_REUSEADDR, true)
        .bind(new InetSocketAddress(PORT))
        .setOption(StandardSocketOptions.IP_MULTICAST_IF, ifc);

dc.join(ADDR, ifc);

Surprisingly this code works and performed as expected, when looking on the NetworkInterface returned by the MulticastSocket.getNetworkInterface() method I saw that it returned an interface named "0.0.0.0" which of course does not exists. Moreover there is no way to get this network interface with any of the NetworkInterface.* factories

Is the solution reliable? can anyone explain why it works and if there is a better way to achieve what I wants?

Upvotes: 3

Views: 2021

Answers (1)

zzzmode
zzzmode

Reputation: 169

I using local address can find LAN devices! so you can try it! e.g NetworkInterface IFC = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());

Upvotes: 1

Related Questions