正如标题所说,您可以使用这两种方法获取客户端的ip。我想知道有没有什么不同。谢谢。
在源代码中有这样的内容
"/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
但我真的不知道其中的含义。
发布于 2012-06-12 21:06:11
来源:
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如下所示
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
来设置环境变量。这是必需的,因为remote_ip
甚至通过本地代理读取ip地址,正如Clowerweb所解释的那样。
发布于 2012-06-12 20:56:10
即使客户端是代理,request.ip
也会返回客户端ip
。
request.remote_ip
更智能,可以获取实际的客户端ip
。只有在所有代理都设置了X-Forwarded-For头的情况下才能做到这一点。
https://stackoverflow.com/questions/10997005
复制相似问题