Using Java to Get the Visitor's Real IP Address

Keywords: JSP Java Apache Spring

               

Main explanation

In JSP, the method to get the IP address of the client is request.getRemoteAddr(), which is effective in most cases. But through Apache,Squid and other reverse proxy software, the real IP address of the client can not be obtained. If reverse proxy software is used, the IP address obtained by request.getRemoteAddr() method is 127.0.0.1 or 192.168.1.110, not the real IP of the client.

After proxy, because of the middle layer between the client and the service, the server can not get the client's IP directly, and the server application can not return the request to the client directly by forwarding the address of the request. However, X-FORWARDED-FOR information is added to HTTP header information for forwarding requests. Used to track the original client IP address and the original client request server address. When we visit index.jsp / it's not that our browser actually accesses the index.jsp file on the server, but that the proxy server accesses index.jsp first, and the proxy server returns the results to our browser. Because the proxy server accesses index.jsp, the IP reality in index.jsp is obtained by request.getRemoteAddr(). Actually, it is the address of the proxy server, not the IP address of the client.

(1) Method 1

So we can get the first way to get the real IP address of the client:

public String getRemortIP(HttpServletRequest request) {  
    if (request.getHeader("x-forwarded-for") == null) {  
        return request.getRemoteAddr();  
    }  
    return request.getHeader("x-forwarded-for");  

}  

(2) Method 2

The second method to obtain the real IP address of the client is:
public 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.getRemoteAddr();  
    }  
    return ip;  
}  

However, if multi-level reverse proxy is adopted, the value of X-Forwarded-For is not only one, but a series of IP values. Which is the real IP of the client?

The answer is to take the first valid IP string in X-Forwarded-For that is not unknown. Such as:
X-Forwarded-For: 192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100

User real IP: 192.168.1.110

(3) Method 3, refer to the codes of netizens

import javax.servlet.http.HttpServletRequest;    /**  * Custom Access Object Tool Class * * Gets the IP address of the object and other information* @author X-rapido  *  */  public class CusAccessObjectUtil {        /**      * Get the user's real IP address without using request.getRemoteAddr(); the reason is that it is possible for the user to use proxy software to avoid the real IP address, * * * However, if a multi-level reverse proxy is passed, the value of X-Forwarded-For is not only one, but a series of IP values. Which is the real user's real IP? * The answer is to take the first valid IP string in X-Forwarded-For that is not unknown. ** For example: X-Forwarded-For: 192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.130,* 192.168.1.100,** User's real IP is 192.168.1.110.** @param request      * @return      */      public static String getIpAddress(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();          }          return ip;      }        }

 /**

* Get Port

 */

public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {   String uri = request.getRequestURI();//Returns the resource name in the request line   String url = request.getRequestURL().toString();//Get the complete url for the client to send the request   String ip = request.getRemoteAddr();//Returns the IP address of the request   String params = request.getQueryString();//Returns the parameter part in the request line   String host=request.getRemoteHost();//Returns the host name of the requesting client   int port =request.getRemotePort();//Returns the port number of the requesting client.   System.out.println(ip);   System.out.println(url);   System.out.println(uri);   System.out.println(params);   System.out.println(host);   System.out.println(port);}

(4) Several methods summarized by netizens:

/**     * Get the client ip address (which can penetrate the proxy)** @param request     * @return     */    public static String getRemoteAddr(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();        }        return ip;    }    private static final String[] HEADERS_TO_TRY = {         "X-Forwarded-For",        "Proxy-Client-IP",        "WL-Proxy-Client-IP",        "HTTP_X_FORWARDED_FOR",        "HTTP_X_FORWARDED",        "HTTP_X_CLUSTER_CLIENT_IP",        "HTTP_CLIENT_IP",        "HTTP_FORWARDED_FOR",        "HTTP_FORWARDED",        "HTTP_VIA",        "REMOTE_ADDR",        "X-Real-IP"};    /***     * Get the client ip address (which can penetrate the proxy)* @param request     * @return     */    public static String getClientIpAddress(HttpServletRequest request) {        for (String header : HEADERS_TO_TRY) {            String ip = request.getHeader(header);            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {                return ip;            }        }        return request.getRemoteAddr();    }    /***     * Get the client ip address (which can penetrate the proxy)* @param request     * @return     */    public static String getClientIpAddr(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_X_FORWARDED_FOR");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("HTTP_X_FORWARDED");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("HTTP_X_CLUSTER_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_FORWARDED_FOR");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("HTTP_FORWARDED");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("HTTP_VIA");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("REMOTE_ADDR");          }          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getRemoteAddr();          }          return ip;      }    public static String getIpAddr(HttpServletRequest request) {        String ip = request.getHeader("X-Real-IP");        if (null != ip && !"".equals(ip.trim())                && !"unknown".equalsIgnoreCase(ip)) {            return ip;        }        ip = request.getHeader("X-Forwarded-For");        if (null != ip && !"".equals(ip.trim())                && !"unknown".equalsIgnoreCase(ip)) {            // get first ip from proxy ip            int index = ip.indexOf(',');            if (index != -1) {                return ip.substring(0, index);            } else {                return ip;            }        }        return request.getRemoteAddr();    }

I used the spring MVC framework and tested the controller code as follows:

package com.web.controller;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.common.util.SystemHWUtil;import com.common.util.WebServletUtil;import com.string.widget.util.ValueWidget;import com.util.JSONPUtil;/*** * Used to test cross-domain *@author huangweii* 29 May 2015*/@Controller@RequestMapping("/cors")public class CORSController {    @ResponseBody    @RequestMapping(value = "/simple",produces=SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF)    public String corsJsonSimple(HttpServletRequest request,String callback){        String content;        Map map=new HashMap();        map.put("username", "Huang Wei");        map.put("age", "27");        map.put("address", "beijing");        content=HWJacksonUtils.getJsonP(map, callback);        System.out.println("getIpAddr:"+WebServletUtil.getIpAddr(request));        System.out.println("getRemoteAddr:"+WebServletUtil.getRemoteAddr(request));        System.out.println("getClientIpAddr:"+WebServletUtil.getClientIpAddr(request));        System.out.println("getClientIpAddress:"+WebServletUtil.getClientIpAddress(request));        return content;    }}

           

Posted by Dave2222 on Mon, 22 Apr 2019 22:09:35 -0700