Skip to content

Commit 562f0ef

Browse files
authored
Merge pull request rails#56805 from fatkodima/optimize-calculating-remote-ip
Optimize calculating remote IP address
2 parents 7b5d711 + 752cc39 commit 562f0ef

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

actionpack/lib/action_dispatch/middleware/remote_ip.rb

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -163,10 +163,11 @@ def calculate_ip
163163
# - REMOTE_ADDR will be the IP that made the request to Rack
164164
ips = forwarded_ips + client_ips
165165
ips.compact!
166+
ips << remote_addr
166167

167168
# If every single IP option is in the trusted list, return the IP that's
168169
# furthest away
169-
filter_proxies(ips + [remote_addr]).first || ips.last || remote_addr
170+
first_non_proxy(ips) || ips[-2] || ips.last
170171
end
171172

172173
# Memoizes the value returned by #calculate_ip and returns it for
@@ -194,9 +195,18 @@ def sanitize_ips(ips) # :doc:
194195
ips
195196
end
196197

197-
def filter_proxies(ips) # :doc:
198-
ips.reject do |ip|
199-
@proxies.any? { |proxy| proxy === ip }
198+
def first_non_proxy(ips) # :doc:
199+
ips.find do |raw_ip|
200+
return unless raw_ip
201+
202+
ip = IPAddr.new(raw_ip)
203+
@proxies.none? do |proxy|
204+
if proxy.is_a?(IPAddr)
205+
proxy.include?(ip)
206+
else
207+
proxy === raw_ip
208+
end
209+
end
200210
end
201211
end
202212
end

0 commit comments

Comments
 (0)