java獲取發起請求使用者的真實ip
阿新 • • 發佈:2018-12-30
public static String getIpAddr(HttpServletRequest request) { try { 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(); if (ip.equals("127.0.0.1")||ip.equals("0:0:0:0:0:0:0:1")) { // 根據網絡卡取本機配置的IP InetAddress inet = InetAddress.getLocalHost(); ip = inet.getHostAddress(); // 對於通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割 if (ip != null && ip.length() > 15) { // "***.***.***.***".length() // = 15 if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } } } if (ip != null && ip.length() > 15) { // "***.***.***.***".length() // = 15 if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } catch (Exception e) { e.printStackTrace(); return null; } }