2010-01-21 48 views
4

我連接到一個URL一個HttpURLConnection類在Java 1.6如何獲得與HttpURLConnection的

遠程IP地址我連接服務器使用DNS輪循到多臺服務器之間共享負載。

如何獲得我實際連接的遠程IP地址?

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 
//I then need something like this! 
log(SUCCESS, "made connection to: " + urlConn.getRemoteIp()); 

回答

4
URL url = new URL("http://yahoo.com"); 
String host = url.getHost(); 
InetAddress address = InetAddress.getByName(host); 
String ip = address.getHostAddress(); 
+1

這可能會給出正確的IP,因爲jvm緩存DNS查詢,除非在jvm上禁用了該功能 – nos 2010-01-21 09:40:19

+1

nos是正確的:如果您已禁用JVM中永久DNS記錄緩存的默認行爲,則此方法可能會返回結果不準確。 – 2011-09-28 23:13:00

4

不是直接的,而是由於JVM緩存DNS查找,您可以使用InetAddress.getByName(服務器名)找到正在使用的實際IP地址,除非你設置了系統屬性「NetworkAddress的。 cache.ttl「來禁用緩存。