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);
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();
props.setProperty("java.net.preferIPv4Stack","true");
System.setProperties(props);

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

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



Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

Thank you for posting this — you saved me at least a 1/2 day of research.

Reply

pfranza Reply:

You’re welcome. When I ran into it a few years ago I nearly pulled my hair out. I was hoping I could save somebody else from that fate.

Reply

Mike Reply:

Yes, thanks, this was great help, you saved me and some coworkers a lot of extra effort.

Reply

Leave a comment

(required)

(required)