Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the static InetAddress.getLoopbackAddress() return?

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

static InetAddress getLoopbackAddress()
Returns the loopback address.

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

The documentation is a bit foggy on the subject:

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

How does Java decide whether to return 127.0.0.1 or the IPv6 pendant ::1?

Or are they both represented by the same InetAdress object?

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

like image 530
magnattic Avatar asked Jan 14 '13 00:01

magnattic


3 Answers

I believe the other answers given here are wrong.

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

Hence, the InetAddress.getLoopbackAddress() will almost always return an IPv4 address. You would have to set java.net.preferIPv6Addresses system properties to true in order to get it to return an IPv6 address.

I don't see any OS dependency for the outcome of this method in the JDK sources. I can't think of an OS where Java would not (with default settings) return an IPv4 address for this method.

like image 181
peterh Avatar answered Nov 04 '22 15:11

peterh


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

As to the returned address, it is OS dependent. However, you can influence the JVM to use IPv4 in priority by passing -Djava.net.preferIPv4Stack=true to the JVM arguments, or by using:

System.setProperty("java.net.preferIPv4Stack" , "true");
like image 4
fge Avatar answered Nov 04 '22 15:11

fge


If you have an IPv6 stack and Java isn't configured to prefer IPv4, it will return ::1.

Otherwise it will return 127.0.0.1.

like image 4
user207421 Avatar answered Nov 04 '22 13:11

user207421