ITPub博客

首页 > IT职业 > IT图书 > 获取客户端真实ip

获取客户端真实ip

IT图书 作者:mpsky 时间:2021-09-09 10:08:18 0 删除 编辑

location /gameExchange {

            proxy_set_header X-Real-IP $remote_addr;

            proxy_pass http://gameExchange;

            proxy_set_header Host $http_host;

            proxy_set_header REMOTE-HOST $remote_addr;

            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

           # proxy_connect_timeout 4;   #nginx跟后端服务器连接超时时间(代理连接超时)

            #proxy_read_timeout 4; #连接成功后,后端服务器响应时间(代理接收超时)

        }

nginx log 格式:

log_format  main  '$remote_addr [$time_local] request_time[$request_time] upto $upstream_addr,'

                      'upresponse_time[$upstream_response_time], "$request" $status $body_bytes_sent '

                      '"$http_user_agent"';


nginx 中如上配置,查看access.log发现$remote_addr打印出来都是内网地址

java 程序获取真实IP代码如下:

public static String getRequestIP(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();

}

//多次反向代理,取第一个IP地址

    if (ip !=null && ip.length() >15) {

if (ip.indexOf(",") >0) {

ip = ip.substring(0, ip.indexOf(","));

}

}

return ip;

}

调用无法获取真实的IP



解决办法: 把$remote_addr替换成$http_x_forwarded_for

location /gameExchange {

            proxy_set_header X-Real-IP $http_x_forwarded_for;

            proxy_pass http://gameExchange;

            proxy_set_header Host $http_host;

            proxy_set_header REMOTE-HOST $remote_addr;

            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

          # proxy_connect_timeout 4;  #nginx跟后端服务器连接超时时间(代理连接超时)

            #proxy_read_timeout 4; #连接成功后,后端服务器响应时间(代理接收超时)

        }

log_format main '$http_x_forwarded_for [$time_local] request_time[$request_time] upto $upstream_addr,'

                      'upresponse_time[$upstream_response_time], "$request" $status $body_bytes_sent '

                      '"$http_user_agent"';




作者:cubotudo
链接:https://www.jianshu.com/p/ffb357df275c


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1806/viewspace-2817200/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-18

  • 博文量
    115
  • 访问量
    14709