InetAddress.getLocalHost() returns APIPA/link-local address in a Windows 2008 SP2 or later version Windows OS with multiple-NICs.

Charles Lee littlee at linux.vnet.ibm.com
Sun Nov 27 22:52:07 PST 2011


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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/net-dev/attachments/20111128/0acea40f/attachment.html 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: patch.contr.v0
Url: http://mail.openjdk.java.net/pipermail/net-dev/attachments/20111128/0acea40f/patch.contr.v0 


More information about the net-dev mailing list