获取客户端有效IP

Nginx配置

若用到Nginx代理时,nginx配置需要添加header配置

location / {
             root   html;
             index  index.jsp;
             proxy_pass  http://dpms80;
             ...
             
             ##将携带客户端真实IP
			 proxy_set_header  Host $host:81;
             proxy_set_header  X-Real-IP  $remote_addr:$remote_port;
             proxy_set_header  X-Forwarded-By  $server_addr:$server_port;
        }

获取IP地址代码

package com.movitech.mobile.cz.base.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class WebUtils {

    private static HttpServletRequest request;
	/**
	 * 这里注入的是Spring的代理类,代理类在获取目标类时,是从线程变量里面获取真实对象的,所以可以这么写
	 **/
    @Autowired
    public WebUtils( HttpServletRequest request) {
        WebUtils.request = request;
    }
    public static  String getIpAddr(){
        String ip = request.getHeader("X-Real-IP");
        try {
            if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
            ip = request.getHeader("X-Forwarded-For");
            if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                int index = ip.indexOf(',');
                if (index != -1) {
                    return ip.substring(0, index);
                } else {
                    return ip;
                }
            } else {
                return request.getRemoteAddr();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ip;
    }
}

你可能感兴趣的:(JAVA,tcp/ip,网络协议,网络)