如何使用httpurlconnection获取远程IP地址

时间:2010-01-21 09:25:41

标签: java http

我正在使用java 1.6中的httpurlconnection连接到一个url

我连接的服务器使用DNS循环来共享多个服务器之间的负载。

如何获取我实际连接的远程IP地址?

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

不直接,但由于JVM正在缓存DNS查找,您可以使用InetAddress.getByName(serverName)查找正在使用的实际IP地址,除非您已将系统属性“networkaddress.cache.ttl”设置为禁用高速缓存中。