工具类-客户端内外网IP判断

 1 private Boolean isOutside(HttpServletRequest request) {
 2         Boolean result = false;
 3         // 获取客户端IP地址
 4         String ip = request.getHeader("x-forwarded-for");
 5         if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
 6             ip = request.getHeader("Proxy-Client-IP");
 7         }
 8         if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
 9             ip = request.getHeader("WL-Proxy-Client-IP");
10         }
11         if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
12             ip = request.getRemoteAddr();
13             if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
14                 InetAddress inet = null;
15                 try {
16                     inet = InetAddress.getLocalHost();
17                     ip = inet.getHostAddress();
18                 } catch (UnknownHostException e) {
19                     e.printStackTrace();
20                 }
21             }
22         }
23         if (!StringUtils.isEmpty(ip) && ip.length() > 15) {
24             ip = ip.substring(0, ip.indexOf(","));
25         }
26         // 判断客户单IP地址是否为内网地址
27         String reg = "(10|172|192)\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})";
28         Pattern p = Pattern.compile(reg);
29         Matcher matcher = p.matcher(ip);
30         result = matcher.find();
31 
32         return result;
33     }

 

你可能感兴趣的:(工具类-客户端内外网IP判断)