What returns static InetAddress.getLoopbackAddress ()?

Java 7 adds a new static method to the java.net.InetAddress class:

 static InetAddress getLoopbackAddress() Returns the loopback address. 

Now I wonder what address will be contained in the result, IP4 or IP6.

The documentation is a bit vague on the topic:

The returned InetAddress will represent an IPv4 loopback address, 127.0.0.1 or an IPv6 loopback address, :: 1. The returned IPv4 loopback address is just one of many in the form of 127 ... *

How does Java decide whether to return 127.0.0.1 or an IPv6 ::1 suspension?

Or are they both represented by the same InetAdress object?

Is the result always the same? Does it depend on my network card?

+7
source share
3 answers

First, there is a fundamental difference between .getLocalHost() and this method: .getLocalHost() will get the address registered with the machine name, while .getLoopbackAddress() will return the local feedback address.

As for the return address, it depends on the OS. However, you can influence the JVM to use IPv4 priority by passing -Djava.net.preferIPv4Stack=true the JVM arguments or using:

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

I believe the other answers given here are incorrect.

Java by default prefers the IPv6 stack (if available), but prefers IPv4 addresses. Pay attention to the subtle difference. This is controlled by the properties of the java.net.preferIPv4Stack and java.net.preferIPv6Addresses , both of which are false by default.

Therefore, InetAddress.getLoopbackAddress() almost always return an IPv4 address. You will need to set the java.net.preferIPv6Addresses system properties to true to force it to return an IPv6 address.

I do not see the OS depending on the result of this method in the JDK sources. I can’t think of an OS where Java will not (with default settings) return an IPv4 address for this method.

+6
source

If you have an IPv6 stack and Java is not configured for IPv4 preference, it will return :: 1.

Otherwise, it will return 127.0.0.1.

+4
source

All Articles