转自: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 //Acquire the IP address of the local machine according to the network card
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 //For the case of multiple proxies, the first IP is the real IP address of the client, and multiple IPs are divided according to ','
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 }
The if() statement at the bottom of the method is to prevent Using the tomcat server, when testing locally, the ip address obtained is 127.0.0.1.
Quoted from: Under the multi-level reverse proxy, Java obtains the real IP address of the requesting client and integrates multiple methods
In JAVA, the server obtains the real IP address of the client
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=326695896&siteId=291194637
Ranking