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?
I using local address can find LAN devices! so you can try it!
e.g
NetworkInterface IFC = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
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