生活随笔
收集整理的這篇文章主要介紹了
java 获取请求客户端的真实IP地址
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載自:http://leiyongping88.iteye.com/blog/1545930
用request.getRemoteAddr();
方法獲取的IP地址是:127.0.0.1或192.168.0.66,而并不是客戶端的真實IP。
經過代理以后,由于在客戶端和服務之間增加了中間層,因此服務器無法直接拿到客戶端的IP,服務器端應用也無法直接通過轉發請求的地址返回給客戶端。但是在轉發請求的HTTP頭信息中,增加了X-FORWARDED-FOR
信息用以跟蹤原有的客戶端IP地址和原來客戶端請求的服務器地址。
public static String getIpAddr(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;
} 像移動網關一樣,iisforward這個ISAPI過濾器也會對request對象進行再包裝,附加一些WLS要用的頭信息。這種情況下,直接用request.getRemoteAddr()是無法取到真正的客戶IP的。
實際的iisforward附加頭如下:
WL-Proxy-Client-IP=215.4.1.29
Proxy-Client-IP=215.4.1.29
X-Forwarded-For=215.4.1.29
WL-Proxy-Client-Keysize=
WL-Proxy-Client-Secretkeysize=
X-WebLogic-Request-ClusterInfo=true
X-WebLogic-KeepAliveSecs=30
X-WebLogic-Force-JVMID=-527489098
WL-Proxy-SSL=false
public static String getIpAddr(HttpServletRequest request) {String ipAddress = null;ipAddress = request.getHeader("x-forwarded-for");if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("Proxy-Client-IP");}if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("WL-Proxy-Client-IP");}if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getRemoteAddr();if(ipAddress.equals("127.0.0.1")){//根據網卡取本機配置的IPInetAddress inet=null;try {inet = InetAddress.getLocalHost();} catch (UnknownHostException e) {e.printStackTrace();}ipAddress= inet.getHostAddress();}}//對于通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15if(ipAddress.indexOf(",")>0){ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));}}return ipAddress;
} ?
轉載于:https://www.cnblogs.com/winner-0715/p/6054951.html
總結
以上是生活随笔為你收集整理的java 获取请求客户端的真实IP地址的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。