Rails 中的 request.remote_ip 和 request.ip 有什么区别? [英] What's the difference between request.remote_ip and request.ip in Rails?

查看:36
本文介绍了Rails 中的 request.remote_ip 和 request.ip 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,您可以通过两种方法获取客户端的IP.我想知道是否有任何差异.谢谢.

As the title goes, you can get the client's ip with both methods. I wonder if there is any differences. Thank you.

在源代码中有

"/usr/local/rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.3/lib/action_dispatch/http/request.rb" 257L, 8741C

"/usr/local/rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.3/lib/action _dispatch/http/request.rb" 257L, 8741C

def ip
  @ip ||= super
end

# Originating IP address, usually set by the RemoteIp middleware.
def remote_ip
  @remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
end

但我真的不知道其中的含义.

but I really don't know the implications.

推荐答案

来自:

module ActionDispatch
  class Request < Rack::Request

    # ...

    def ip
      @ip ||= super
    end

    def remote_ip
      @remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
    end

    # ...

  end
end

Rack::Request 看起来像这样

where Rack::Request looks like this

module Rack
  class Request
     def ip
      remote_addrs = split_ip_addresses(@env['REMOTE_ADDR'])
      remote_addrs = reject_trusted_ip_addresses(remote_addrs)

      return remote_addrs.first if remote_addrs.any?

      forwarded_ips = split_ip_addresses(@env['HTTP_X_FORWARDED_FOR'])

      if client_ip = @env['HTTP_CLIENT_IP']
        # If forwarded_ips doesn't include the client_ip, it might be an
        # ip spoofing attempt, so we ignore HTTP_CLIENT_IP
        return client_ip if forwarded_ips.include?(client_ip)
      end

      return reject_trusted_ip_addresses(forwarded_ips).last || @env["REMOTE_ADDR"]
    end
  end
end 

所以 remote_ip 优先于 action_dispatch.remote_ip.这是由 ActionDispatch::RemoteIp 中间件设置的.您可以在该中间件的源代码中看到它在被调用时正在检查欺骗攻击,因为它正在调用 GetIp.new 来设置该环境变量.正如 Clowerweb 解释的那样,这是必需的,因为 remote_ip 甚至通过本地代理读取 IP 地址.

So remote_ip gives precedence to action_dispatch.remote_ip. That is being set by ActionDispatch::RemoteIp middleware. You can see in that middleware's source that it's checking for spoofing attacks when being called, since it's calling GetIp.new to set that env variable. That's needed since remote_ip reads the ip address even through the local proxies, as Clowerweb explains.

这篇关于Rails 中的 request.remote_ip 和 request.ip 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆