Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set java.net.preferIPv4Stack=true at runtime?

I need to disable IPv6. For that the java documentation indicates setting jvm property java.net.preferIPv4Stack=true.

But I don't understand how to do it from the code itself.

Many forums demonstrated doing it from the command prompt, but I need to do it at runtime.

like image 463
Caffeinated Coder Avatar asked Mar 27 '12 01:03

Caffeinated Coder


4 Answers

You can use System.setProperty("java.net.preferIPv4Stack" , "true");

This is equivalent to passing it in the command line via -Djava.net.preferIPv4Stack=true

like image 123
Kal Avatar answered Oct 16 '22 14:10

Kal


Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:

http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.

Specifically for java web start set the environment variable:

JAVAWS_VM_ARGS

and for applets:

_JPI_VM_OPTIONS

e.g.

_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true

Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.

like image 24
Jamie Love Avatar answered Oct 16 '22 15:10

Jamie Love


I ran into this very problem trying to send mail with javax.mail from a web application in a web server running Java 7. Internal mail server destinations failed with "network unreachable", despite telnet and ping working from the same host, and while external mail servers worked. I tried

System.setProperty("java.net.preferIPv4Stack" , "true");

in the code, but that failed. So the parameter value was probably cached earlier by the system. Setting the VM argument

-Djava.net.preferIPv4Stack=true

in the web server startup script worked.

One further bit of evidence: in a very small targeted test program, setting the system property in the code did work. So the parameter is probably cached when the first Socket is used, probably not just as the JVM starts.

like image 9
dtc Avatar answered Oct 16 '22 15:10

dtc


well,

I used System.setProperty("java.net.preferIPv4Stack" , "true"); and it works from JAVA, but it doesn't work on JBOSS AS7.

Here is my work around solution,

Add the below line to the end of the file ${JBOSS_HOME}/bin/standalone.conf.bat (just after :JAVA_OPTS_SET )

set "JAVA_OPTS=%JAVA_OPTS% -Djava.net.preferIPv4Stack=true"

Note: restart JBoss server

like image 3
Hussein mahyoub Avatar answered Oct 16 '22 14:10

Hussein mahyoub