首页 > 编程语言 > 详细

java获取客户端ip地址工具类

时间:2019-04-22 19:14:09      阅读:129      评论:0      收藏:0      [点我收藏+]
 1 public class IpUtils {
 2     private static final String[] HEADERS = {
 3         "X-Forwarded-For",
 4         "Proxy-Client-IP",
 5         "WL-Proxy-Client-IP",
 6         "HTTP_X_FORWARDED_FOR",
 7         "HTTP_X_FORWARDED",
 8         "HTTP_X_CLUSTER_CLIENT_IP",
 9         "HTTP_CLIENT_IP",
10         "HTTP_FORWARDED_FOR",
11         "HTTP_FORWARDED",
12         "HTTP_VIA",
13         "REMOTE_ADDR",
14         "X-Real-IP"
15     };
16 
17     /**
18      * 判断ip是否为空,空返回true
19      * @param ip
20      * @return
21      */
22     public static boolean isEmptyIp(final String ip){
23         return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip));
24     }
25 
26 
27     /**
28      * 判断ip是否不为空,不为空返回true
29      * @param ip
30      * @return
31      */
32     public static boolean isNotEmptyIp(final String ip){
33         return !isEmptyIp(ip);
34     }
35 
36     /***
37      * 获取客户端ip地址(可以穿透代理)
38      * @param request HttpServletRequest
39      * @return
40      */
41     public static String getIpAddress(HttpServletRequest request) {
42         String ip = "";
43         for (String header : HEADERS) {
44             ip = request.getHeader(header);
45             if(isNotEmptyIp(ip)) {
46                 break;
47             }
48         }
49         if(isEmptyIp(ip)){
50             ip = request.getRemoteAddr();
51         }
52         if(isNotEmptyIp(ip) && ip.contains(",")){
53             ip = ip.split(",")[0];
54         }
55         if("0:0:0:0:0:0:0:1".equals(ip)){
56             ip = "127.0.0.1";
57         }
58         return ip;
59     }
60 
61 
62     /**
63      * 获取本机的局域网ip地址,兼容Linux
64      * @return String
65      * @throws Exception
66      */
67     public String getLocalHostIP() throws Exception{
68         Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
69         String localHostAddress = "";
70         while(allNetInterfaces.hasMoreElements()){
71             NetworkInterface networkInterface = allNetInterfaces.nextElement();
72             Enumeration<InetAddress> address = networkInterface.getInetAddresses();
73             while(address.hasMoreElements()){
74                 InetAddress inetAddress = address.nextElement();
75                 if(inetAddress != null && inetAddress instanceof Inet4Address){
76                     localHostAddress = inetAddress.getHostAddress();
77                 }
78             }
79         }
80         return localHostAddress;
81     }
82 
83 }

 

java获取客户端ip地址工具类

原文:https://www.cnblogs.com/Charlie-Gou/p/10751580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!