在Ruby on Rails中获取主机名或者IP
我正在维护Ruby on Rails应用程序,并且正在寻找一种简单的方法来查找我所在盒子的主机名或者IP地址(因为它是VM,并且新实例可能具有不同的主机名或者IP地址) 。在Ruby on Rails中,有没有一种快速简便的方法来做到这一点?
编辑:下面的答案是正确的,但是提供的澄清Craig很有用(另请参见答案中提供的链接):
The [below] code does NOT make a connection or send any packets (to 64.233.187.99 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket.
解决方案
回答
尝试:Request.remote_ip
remote_ip() Determine originating IP address. REMOTE_ADDR is the standard but will fail if the user is behind a proxy. HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR are set by proxies so check for these if REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- delimited list in the case of multiple chained proxies; the last address which is not trusted is the originating IP.
更新:
糟糕,对不起,我误读了文档。
回答
试试这个:
host = `hostname`.strip # Get the hostname from the shell and removing trailing \n puts host # Output the hostname
回答
我们可能会发现自己在每台计算机上都有多个IP地址(127.0.0.1、192.168.0.1等)。如果我们使用* NIX作为操作系统,建议我们使用hostname
,然后在其上运行DNS查找。我们应该能够使用/ etc / hosts定义本地主机名,以解析为该计算机的IP地址。 Windows上有类似的功能,但是自从Windows 95成为最新技术以来,我就没有使用它。
另一种选择是点击查找服务,例如WhatIsMyIp.com。这些家伙会把真实IP地址发给我们。我们也可以根据需要在本地服务器上轻松地使用Perl脚本进行设置。我相信从%ENV输出远程IP的3行左右的代码应该可以覆盖我们。
回答
来自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中获取主机名的一种简单方法是:
require 'socket' hostname = Socket.gethostname
问题在于,这依赖于主机知道其自身的名称,因为它使用了gethostname
或者uname
系统调用,因此对于原始问题将不起作用。
从功能上讲,这与"主机名"答案相同,而无需调用外部程序。主机名可以是完全限定的,也可以不是完全限定的,具体取决于计算机的配置。
IP地址
从ruby 1.9开始,我们还可以使用Socket库获取本地地址列表。 ip_address_list返回一个AddrInfo对象的数组。如何选择取决于我们要做什么以及拥有多少接口,但是以下示例仅选择第一个非环回IPV4 IP地址作为字符串:
require 'socket' ip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address
回答
将突出显示的部分放在反引号中:
`dig #{request.host} +short`.strip # dig gives a newline at the end
如果我们不在乎它是否是IP,也可以使用request.host
。
回答
最简单的是controller.rb中的" host_with_port"
host_port= request.host_with_port