package com.yc.utils; import javax.servlet.http.HttpServletRequest; public class IPUtil { /** * 通过request获得客户端ip * @param request * @return */ 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; } public static String getMainDomain(HttpServletRequest request) { String domain = request.getServerName(); int tempIndex = -1; if(-1 != (tempIndex=domain.lastIndexOf("."))){ String temp = domain.substring(0,tempIndex); tempIndex = temp.lastIndexOf("."); domain = domain.substring(tempIndex+1); } return domain; } /** * 验证ip是否合法 * * @param text * ip地址 * @return 验证信息 */ public static boolean ipCheck(String text) { if (text != null && !text.isEmpty()) { // 定义正则表达式 String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; // 判断ip地址是否与正则表达式匹配 if (text.matches(regex)) { // 返回判断信息 return true; } else { // 返回判断信息 return false; } } // 返回判断信息 return false; } }