Java获取访客IP地址

➢ 获取IP地址

在开发工作中,我们常常需要获取客户端的IP

nginx配置

为了拿到真实的IP地址,避免代理等错误源,需要在nginx配置

location / {
            # 指向当前的某个服务端口(根据服务单独java打包jar开启对应的服务)
            proxy_pass   http://127.0.0.1:端口号;

            # 这里配置java获取客户端真实的ip地址(避免因为nginx反向代理造成ip 127.0.0.1等其他错误现象)
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            set $Real $http_x_forwarded_for;
            if ( $Real ~ (\d+)\.(\d+)\.(\d+)\.(\d+),(.*) ){
                set $Real $1.$2.$3.$4;
            }
            proxy_set_header X-Real-Ip $Real;
        }
java API 获取
//获取ip地址
    @GetMapping(value = "/getIp")
    @ResponseBody
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值,第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println("getRemoteAddr ip: " + ip);
        }
        System.out.println("获取客户端ip: " + ip);
        return ip;
    }
Tips

ip可以定位用户的网段,稍作处理可以定位访客的大致地理位置,甚至精确到门牌号