不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2023-11-07 11:38:03  修改时间:2024-05-08 07:26:04  分类:Java框架/系统  编辑

Java直接取IP的方法:

import javax.servlet.http.HttpServletRequest;
request.getRemoteAddr();

但这个方法只适用于没有使用nginx等代理的项目,如果是有做代理的项目,在每通过一次代理的时候都需要把真实ip存好,这样到了后台服务器时我们才能取到真实ip而不是代理服务器的ip。

以nginx代理为例:

我们需要在nginx中进行配置一些请求头存放信息:

server {
    listen        6000;    #监听端口 http的网络端口80 https 443 ssl (这个要配置秘钥)
    server_name  localhost;   
    proxy_set_header Host $http_host;     
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;

    location / {
        root   html;
        index  index.html index.htm;
    }
}

$remote_addr:存放的是当前请求来的ip,常用存放真实ip的头

X-Forwarded-For:它的值是每经过一层代理,它会将每层获取的ip以逗号分隔,而请求的真实ip将会被放在第一个,我们取这个即可

方式一:直接调用Hutool工具的api,获取真实ip:

import cn.hutool.extra.servlet.ServletUtil;

public static String getIpAddr(HttpServletRequest request) {
    String clientIP = ServletUtil.getClientIP(request, null);
    System.out.println("获取到的ip=" + clientIP);
    return clientIP;
}

方式二:

/**
 * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
 * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值
 *
 * @return ip
 */
public static 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;
}

 

 

参考:

nginx代理获取用户ip为127.0.0.1解决方案