Hi guys,
When we call InetAddress.getLocalHost(), we usually return the first
entry of inet address array. The array keeps the same order as
getaddrinfo gets (duplication has been removed).
In Windows 2008 sp2 or later version Windows OS with multiple NICs,
getaddrinfo() sorts the Addresses and linklocal/APIPA address appears
first now. So user will get a APIPA address even if a more useful
address is available. A simple test case will show this problem:
/public class InetTest {
public static void main(String[] args) throws Exception{
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr);
System.out.println(addr.isLinkLocalAddress());
}
}/
I'd like to propose a patch, which get the useful address info, if
available, in the InetAddress.java (attached and pasted). Anyone
interested in it ?
diff --git src/share/classes/java/net/InetAddress.java
src/share/classes/java/net/InetAddress.java
index 8758cab..4cbf890 100644
--- src/share/classes/java/net/InetAddress.java
+++ src/share/classes/java/net/InetAddress.java
@@ -1443,9 +1443,17 @@ class InetAddress implements java.io.Serializable {
uhe2.initCause(uhe);
throw uhe2;
}
- cachedLocalHost = localAddrs[0];
+ for (InetAddress addr : localAddrs) {
+ if (!addr.isLinkLocalAddress()) {
+ cachedLocalHost = addr;
+ break;
+ }
+ }
+ if (cachedLocalHost == null) {
+ cachedLocalHost = localAddrs[0];
+ }
cacheTime = now;
- ret = localAddrs[0];
+ ret = cachedLocalHost;
}
}
return ret;
--
Yours Charles
diff --git src/share/classes/java/net/InetAddress.java
src/share/classes/java/net/InetAddress.java
index 8758cab..4cbf890 100644
--- src/share/classes/java/net/InetAddress.java
+++ src/share/classes/java/net/InetAddress.java
@@ -1443,9 +1443,17 @@ class InetAddress implements java.io.Serializable {
uhe2.initCause(uhe);
throw uhe2;
}
- cachedLocalHost = localAddrs[0];
+ for (InetAddress addr : localAddrs) {
+ if (!addr.isLinkLocalAddress()) {
+ cachedLocalHost = addr;
+ break;
+ }
+ }
+ if (cachedLocalHost == null) {
+ cachedLocalHost = localAddrs[0];
+ }
cacheTime = now;
- ret = localAddrs[0];
+ ret = cachedLocalHost;
}
}
return ret;