java伺服器獲取客戶端ip
在寫服務端程式碼時,有時需要對客戶端ip做認證,比如限制只有某些ip能訪問,或者1個ip1天只能訪問幾次。最近就碰到個需要限制ip的情況,從網上找了一些伺服器獲取客戶端ip的方法,說的都不太完善,這裡整理一下。
獲取客戶端ip其實就是從request中取,從header取或者直接request.getRemoteAddr()。
public static String getRemoteIpAddr() { HttpServletRequest request = getRequest(); 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(); } int index = ip.indexOf(","); if(index != -1){ return ip.substring(0,index); } else { return ip; } }
public static HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
}
如果使用了反向代理軟體,將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地址和原來客戶端請求的伺服器地址。
可是,如果通過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串Ip值,究竟哪個才是真正的使用者端的真實IP呢?
答案是取X-Forwarded-For中第一個非unknown的有效IP字串。
如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100使用者真實IP為: 192.168.1.110
參考原文地址:
http://blog.sina.com.cn/s/blog_a0949eec01013uxg.html
http://blog.csdn.net/songylwq/article/details/7701718