2

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?

user207421
  • 289,834
  • 37
  • 266
  • 440
bennyl
  • 2,643
  • 2
  • 26
  • 42
  • Hava a look here http://stackoverflow.com/questions/19392173/multicastsocket-constructors-and-binding-to-port-or-socketaddress – Shar1er80 May 31 '15 at 23:35
  • Well evidently `MulticastSocket.getNetworkInterface()` returns a magical `0.0.0.0 NetworkInterface` you can't get any other way. It wouldn't do that if you had called `MulticastSocket.setNetworkInterface()`. It's curious that the NIO version doesn't have a one-argument `join()` method. – user207421 May 31 '15 at 23:49

1 Answers1

1

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

zzzmode
  • 171
  • 4