Java的Ip操作工具类

Java的Ip操作工具类教程

在 web 项目中,有的时候,我们需要获取相应的 ip 地址,然后对该 ip 地址做一些控制,比如 白名单啊,黑名单啊啥的,限制一部分 ip 做一些事情等等。前提是我们的项目是 web 项目。

IpUtil

package net.haicoder; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; /** * @author 嗨客网 * @description */ public class IpUtil { /** * 逗号,分隔 */ static final Pattern COMMA_PATTERN = Pattern.compile(","); private IpUtil() { } public static String getRemoteIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (isNotIp(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (isNotIp(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (isNotIp(ip)) { ip = request.getRemoteAddr(); } if (isIp(ip)) { ip = COMMA_PATTERN.split(ip)[0]; } return ip; } /** * 判断ip地址是正确的 * @param ip ip地址 * @return true-是,false-否 */ private static boolean isIp(String ip) { return !isNotIp(ip); } /** * 判断ip地址是不正确的 * @param ip ip地址 * @return true-是,false-否 */ private static boolean isNotIp(String ip) { return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip); } public static long ipToLong(String ip) { int firstDot = ip.indexOf('.'); int secDot = ip.indexOf('.', firstDot + 1); int thirdDot = ip.indexOf('.', secDot + 1); if (-1 == firstDot || -1 == secDot || -1 == thirdDot) { throw new IllegalArgumentException("illegal argument"); } String firstStr = ip.substring(0, firstDot); String secStr = ip.substring(firstDot + 1, secDot); String thirdStr = ip.substring(secDot + 1, thirdDot); String fourthStr = ip.substring(thirdDot + 1, ip.length()); long firstLong = Long.parseLong(firstStr); firstLong = firstLong << 24; long secLong = Long.parseLong(secStr); secLong = secLong << 16; long thirdLong = Long.parseLong(thirdStr); thirdLong = thirdLong << 8; long fourthLong = Long.parseLong(fourthStr); return firstLong + secLong + thirdLong + fourthLong; } public static String longToIp(long ipLong) { long temp = 0; long first = ipLong / (1 << 24); temp = ipLong % (1 << 24); long sec = temp / (1 << 16); temp = temp % (1 << 16); long third = temp / (1 << 8); temp = temp % (1 << 8); long fourth = temp; StringBuilder sb = new StringBuilder(); sb.append(first).append(".").append(sec).append(".").append(third).append(".").append(fourth); return sb.toString(); } }