新手问题 Grape 如何获取客户端的 IP 地址?

kingwkb · 2013年06月20日 · 最后由 geekontheway 回复于 2016年08月22日 · 7684 次阅读

ip

request.remote_ip

#1 楼 @tumayun 这个获取不到

如果使用 nignex 的话,在配置文件中加入 proxy_set_header X-Real-IP $remote_addr; 然后用env["X-Real-IP"]可以取到

#3 楼 @Vincent178 这样的话在本地开发环境中不是获取不到 ip 了?

#4 楼 @kingwkb 本地得到的 ip 就是 127.0.0.1

#5 楼 @Vincent178 我在本地用 env["REMOTE_ADDR"] 取到的也是 127.0.0.1,如果 production 环境下前面用 nginx 代理,REMOTE_ADDR 还能用么

#6 楼 @kingwkb env["X-Real-IP"] 在 production 环境下,就能取到用户的真实 ip,而不是你 nginx 的 ip 另,你取的时候 env["REMOTE_ADDR"] 是取不到的,要用 env["X-Real-IP"] 才能取到,同样可以设置

proxy_set_header    X-Real-IP   $remote_addr;
proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;

然后用 env['X-Forwarded-For'] 来取到真实 ip, 实际上,rails 在写 remote_ip 方法的时候,已经把env['X-Forwarded-For']这个 header 取真实 ip 的情况考虑进入了,具体可以参考 rails 的源代码

#7 楼 @Vincent178 rails 里面 remote_ip 太复杂了,我知道这样是为了获取客户端真实的 IP,过滤掉中间代理的 IP,我还是直接用 X-Real-IP 得了,Grape 就没有一个类似 Rails 里面的写的完整的获取 IP 的方法么,或者直接使用 Rails 的 remote_ip

#8 楼 @kingwkb 不清楚,Grape 不会。。。

env['X-Forwarded-For']里的内网 IP,最后一个 IP 就是客户端的外网 IP。

#9 楼 @Vincent178 env["X-Real-IP"] 在开发环境下获取不到

#11 楼 @kingwkb 需要设置 nginx 的 header

#12 楼 @Vincent178 貌似不行。设置了 nginx 的 header 也不行。不过还是很感谢你的回复。 后来深入挖掘了一下,发现虽然在 Grape 代码中我没办法把 IP 记录下来,但我查看 Nginx 的访问日志,发现里面记录了 IP $ tail -f /var/log/nginx/access.log 也算暂时解决了问题。

不要怪 Grape 哦,Grape 里面直接用 headers["X-Real-IP"] 就可以了嘛。 在 Nginx 里面设置: proxy_set_header X-Real-IP $remote_addr;

文档中 Remote IP 一节中提到了

https://github.com/ruby-grape/grape#remote-ip

class API < Grape::API
  use ActionDispatch::RemoteIp

  helpers do
    def client_ip
      env['action_dispatch.remote_ip'].to_s
    end
  end

  get :remote_ip do
    { ip: client_ip }
  end
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号