本文介绍了在Ruby on Rails中获取主机名或IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在维护Ruby on Rails应用程序,并且正在寻找一种简单的方法来查找我所在盒子的主机名或IP地址(因为它是VM,并且新实例可能具有不同的主机名或IP地址).在Ruby on Rails中有快速简便的方法吗?

I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?

以下答案是正确的,但提供的Craig澄清说明很有用(另请参见答案中提供的链接):

The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):

推荐答案

来自 coderrr.wordpress.com :

require 'socket'

def local_ip
  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect '64.233.187.99', 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

# irb:0> local_ip
# => "192.168.0.127"

这篇关于在Ruby on Rails中获取主机名或IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 11:08