Created
October 12, 2008 20:05
-
-
Save no6v/16462 to your computer and use it in GitHub Desktop.
local_ip for rails' controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ::ActionController | |
class Request | |
unless method_defined?(:local_ip) | |
require "socket" | |
require "ipaddr" | |
def local_ip | |
f = Socket.do_not_reverse_lookup | |
Socket.do_not_reverse_lookup = true | |
ip = IPAddr.new(remote_ip) | |
UDPSocket.open(ip.family) do |s| | |
s.connect(ip.to_s, 1) | |
IPAddr.new(s.addr.last).native.to_s | |
end | |
ensure | |
Socket.do_not_reverse_lookup = f | |
end | |
end | |
end | |
end | |
if __FILE__ == $0 | |
require "test/unit" | |
class LocalIPTest < Test::Unit::TestCase | |
def test_local_ip | |
request = ::ActionController::TestRequest.new | |
request.remote_addr = "127.0.0.1" | |
assert_equal "127.0.0.1", request.local_ip | |
request.remote_addr = "127.0.0.2" | |
assert_equal "127.0.0.2", request.local_ip | |
request.remote_addr = "::1" | |
assert_equal "::1", request.local_ip | |
request.remote_addr = "::ffff:127.0.0.1" | |
assert_equal "127.0.0.1", request.local_ip | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment