Get the real ip address of the client in the background

Keywords: JSP Apache Nginx network

In JSP, the method to get the IP address of the client is: request.getRemoteAddr(), which is effective in most cases. However, after passing Apache, Squid, nginx and other reverse proxy software, the real IP address of the client cannot be obtained. After the proxy, because the middle layer is added between the client and the service, the server can not get the IP of the client directly, and the application of the server can not directly return to the client through the address of forwarding request. However, x-forwarded-for information is added to the HTTP header for forwarding requests. To track the original client IP address and the server address requested by the original client.

Then obtaining the real ip can be divided into two steps:

1. Get the HttpServletRequest object, which contains the relevant information requested by the client

2. Get the required ip address from the HttpServletRequest object

   

@Autowired
private HttpServletRequest request;

        

    private String getIpAddr(HttpServletRequest request) {   
           String ip = request.getHeader("x-forwarded-for");   
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getHeader("Proxy-Client-IP");   
           }   
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getHeader("WL-Proxy-Client-IP");   
           }   

           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getHeader("HTTP_CLIENT_IP");   
           } 
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getHeader("HTTP_X_FORWARDED_FOR");   
           } 
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getRemoteAddr();   
               if(ip.equals("127.0.0.1")){     
                   //Access the IP configured for this computer according to the network card     
                   InetAddress inet=null;     
                   try {     
                       inet = InetAddress.getLocalHost();     
                   } catch (Exception e) {     
                       e.printStackTrace();     
                   }     
                   ip= inet.getHostAddress();     
               }  
           }   
           // In the case of multiple agents, the first IP is the real IP of the client, and multiple IPS are divided by ','  
           if(ip != null && ip.length() > 15){    
               if(ip.indexOf(",")>0){     
                   ip = ip.substring(0,ip.indexOf(","));     
               }     
           }     
           return ip;   
    } 

 

Posted by azylka on Wed, 20 Nov 2019 10:24:20 -0800