Java multicast untold aspect

One of the elements not clearly stated if reading the java multicast documentation and examples found on the net is that if you create a multicast receiver this will NOT listed to all available interfaces. Instead one must specify the desired interface because otherwise the MulticastSocket will only listen to the first active (default?) interface. Here is an example of code which specifies exactly the interface to listen to:



MulticastSocket s = new MulticastSocket(port);
#clearly specify the desired interface to listen

byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);



If you don’t do that it is possible in cases where multiple interfaces are present to find yourself never receiving the multicast packets. Here is an useful command on linux to show the multicast packets

 tcpdump -i eth1 -n -v udp and ip multicast

One possible solution would be to listen on all interfaces, here is some code (available since java 1.4) to show the interfaces:

Enumeration ints = NetworkInterface.getNetworkInterfaces();
while (ints.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) ints.nextElement();
Enumeration ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = (InetAddress) ips.nextElement();

Leave a Reply