首页 > 代码库 > IPUtils 工具类
IPUtils 工具类
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; } }
IPUtils 工具类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。