在JSP里,獲取客戶端的IP地址的方法是:request.getRemoteAddr() ,這種方法在大部分情況下都是有效的。但是在通過了Apache,Squid等反向代理軟件就不能獲取到客戶端的真實IP地址了。
如果使用了反向代理軟件,將http://192.168.1.110:2046/ 的URL反向代理為http://www.xxx.com/ 的URL時,用request.getRemoteAddr() 方法獲取的IP地址是:127.0.0.1 或 192.168.1.110 ,而並不是客戶端的真實IP。
經過代理以后,由於在客戶端和服務之間增加了中間層,因此服務器無法直接拿到客戶端的IP,服務器端應用也無法直接通過轉發請求的地址返回給客戶端。但是在轉發請求的HTTP頭信息中,增加了X-FORWARDED-FOR信息。用以跟蹤原有的客戶端IP地址和原來客戶端請求的服務器地址。當我們訪問http://www.xxx.com/index.jsp/ 時,其實並不是我們瀏覽器真正訪問到了服務器上的index.jsp文件,而是先由代理服務器去訪問http://192.168.1.110:2046/index.jsp ,代理服務器再將訪問到的結果返回給我們的瀏覽器,因為是代理服務器去訪問index.jsp的,所以index.jsp中通過request.getRemoteAddr() 的方法獲取的IP實際上是代理服務器的地址,並不是客戶端的IP地址。
於是可得出獲得客戶端真實IP地址的方法一:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/**
* The Class IpUtils.
*
*/
public abstract class IpUtils {
/**
* Gets the client ip addr.
*
* @param request the request
* @return the client ip addr
*/
public static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* Gets the real ips.
*
* @return the real ips
*/
public static List<String> getRealIps() {
List<String> ips = new ArrayList<String>();
String localip = null;// 本地IP,如果沒有配置外網IP則返回它
String netip = null;// 外網IP
Enumeration<NetworkInterface> netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
return null;
}
InetAddress ip = null;
boolean finded = false;// 是否找到外網IP
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外網IP
netip = ip.getHostAddress();
ips.add(netip);
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 內網IP
localip = ip.getHostAddress();
ips.add(localip);
}
}
}
return ips;
}
/**
* Gets the real ip.
*
* @return the real ip
*/
public static String getRealIp() {
return getRealIps().iterator().next();
}
}