How to extract IP Address in Spring MVC Controller get call?

后端 未结 9 564
长发绾君心
长发绾君心 2020-11-28 04:04

I am working on Spring MVC controller project in which I am making a GET URL call from the browser -

Below is the url by which I am making a GET call from the browse

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 04:38

    private static final String[] IP_HEADER_CANDIDATES = {
                "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"
        };
    
        public static String getIPFromRequest(HttpServletRequest request) {
            String ip = null;
            if (request == null) {
                if (RequestContextHolder.getRequestAttributes() == null) {
                    return null;
                }
                request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            }
    
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!StringUtils.isEmpty(ip))
                return ip;
    
            for (String header : IP_HEADER_CANDIDATES) {
                String ipList = request.getHeader(header);
                if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                    return ipList.split(",")[0];
                }
            }
    
            return request.getRemoteAddr();
        }
    

    I combie the code above to this code work for most case. Pass the HttpServletRequest request you get from the api to the method

提交回复
热议问题