package util; import com.google.common.base.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; /** * Created by nolan on 16/9/22. * description: IP相关服务类,支持ip地址的获取、地理位置转换. */ public class IPAddrUtil { protected static Logger logger = LoggerFactory.getLogger(IPAddrUtil.class); static { IP.load(IPAddrUtil.class.getClassLoader().getResource("17monipdb.dat").getFile()); } /** * 获取IP地址 * * @param httpServletRequest 请求实体 * @return */ public static String getIpAddr(HttpServletRequest httpServletRequest) { final String header = httpServletRequest.getHeader("x-forwarded-for"); if (Strings.isNullOrEmpty(header)) { return ""; } String[] ipStr = header.split(","); String ip = ipStr[ipStr.length - 1].replace(" ", ""); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = httpServletRequest.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = httpServletRequest.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = httpServletRequest.getRemoteAddr(); } return ip; } /** * 获取IP地址 * * @param httpServletRequest 请求实体 * @return */ public static String getIpAddrNew(HttpServletRequest httpServletRequest) { if (httpServletRequest.getHeader("x-forwarded-for") == null) { return httpServletRequest.getRemoteAddr(); } String[] ipStr = httpServletRequest.getHeader("x-forwarded-for").split(","); String ip=ipStr[ipStr.length-1].replace(" ",""); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = httpServletRequest.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = httpServletRequest.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = httpServletRequest.getRemoteAddr(); } return ip; } /** * 根据ip地址转换成对应省份 * * @param ipAddr ip地址 * @return */ public static String getLocationFromIpAddr(String ipAddr) { if (ipAddr == null || ipAddr.isEmpty()) { return "unknown"; } try { String[] tmp = IP.find(ipAddr); return String.format("%s", tmp[1]); } catch (Exception e) { logger.error("fail to parse ip:" + ipAddr); return "unknown"; } } /** * 根据ip地址转换成对应地理位置 * * @param ipAddr ip地址 * @return */ public static String getAllLocationFromIpAddr(String ipAddr) { if (ipAddr == null || ipAddr.isEmpty()) { return "unknown-unknown-unknown"; } try { String[] tmp = IP.find(ipAddr); return String.format("%s-%s-%s", tmp[0],tmp[1],tmp[2]); } catch (Exception e) { logger.error("fail to parse ip:" + ipAddr); return "unknown-unknown-unknown"; } } }