package com.hxqc.basic.dependency.util; import org.apache.commons.lang.StringUtils; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * 获得IP地址工具类 * * @author huyj * @Created 2017-05-23 16:34 */ public class IPUtils { /** * 获取访问用户的客户端IP(适用于公网与局域网). */ public static final String getIpAddr(final HttpServletRequest request) throws Exception { if (request == null) { throw (new Exception("getIpAddr method HttpServletRequest Object is null")); } String ipString = request.getHeader("x-forwarded-for"); if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) { ipString = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) { ipString = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) { ipString = request.getRemoteAddr(); } // 多个路由时,取第一个非unknown的ip final String[] arr = ipString.split(","); for (final String str : arr) { if (!"unknown".equalsIgnoreCase(str)) { ipString = str; break; } } return ipString; } /** * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; * * @param request * @return * @throws IOException */ public final static String getIpAddress(HttpServletRequest request) throws IOException { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; } }