在JAVA中,服务端获取客户端真正的IP地址

转自:http://www.cnblogs.com/xjh5201314/p/6591174.html
1 public static String getIpAddress(HttpServletRequest request){
2        
3         String ipAddress = request.getHeader("x-forwarded-for");
4        
5         if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
6             ipAddress = request.getHeader("Proxy-Client-IP");
7         }
8         if (ipAddress == null || ipAddress.length() == 0 || "unknow".equalsIgnoreCase(ipAddress)) {
9             ipAddress = request.getHeader("WL-Proxy-Client-IP");
10         }
11         if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
12             ipAddress = request.getRemoteAddr();
13            
14             if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
15                 //根据网卡获取本机配置的IP地址
16                 InetAddress inetAddress = null;
17                 try {
18                     inetAddress = InetAddress.getLocalHost();
19                 } catch (UnknownHostException e) {
20                     e.printStackTrace();
21                 }
22                 ipAddress = inetAddress.getHostAddress();
23             }
24         }
25        
26         //对于通过多个代理的情况,第一个IP为客户端真实的IP地址,多个IP按照','分割
27         if(null != ipAddress && ipAddress.length() > 15){
28             //"***.***.***.***".length() = 15
29             if(ipAddress.indexOf(",") > 0){
30                 ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
31             }
32         }
33        
34         return ipAddress;
35     }
方法最下方的if()语句,是为了防止使用tomcat服务器,在本地测试的时候,得出的ip地址是127.0.0.1的问题。
引用自:多级反向代理下,Java获取请求客户端的真实IP地址多中方法整合

猜你喜欢

转载自lysj102289.iteye.com/blog/2396276
今日推荐