Setting Multicast Time To Live in Java

I know that this seems trivial, but there are a few gotchas that have burned me a few times so I thought I would post the solution here.

The API will lead you to write this

MulticastSocket socket = new MulticastSocket(6000);<br /> socket.setTimeToLive(16);

And you’ll feel pretty good about it, but then you will deploy your software only to find out that the packets aren’t clearing the first router hop. Then you’ll fire up ethereal and upon inspection you will notice that the TTL in the packet is 0. What the hell? You can clearly see where you set it to 16.

There is a small hiccup inside java where they have been blending the java.net API to be stack agnostic and if you are on a dual stack (IPv4 & IPv6) capable machine and are only using the IPv4 stack you need to notify the JVM by setting a special system property. This can be done two ways:

First you can set the property in code

Properties props = System.getProperties();<br /> props.setProperty("java.net.preferIPv4Stack","true");<br /> System.setProperties(props);<br />

I agree with you that the third line doesn’t look nessecary, but in my experiance it is. Or you can set this option from the command-line:

java -Djava.net.preferIPv4Stack=true -jar program.jar<br />

I hope this post helps, because I was ready to tear my hair out.