在 Ruby on Rails 中获取主机名或 IP [英] Getting the Hostname or IP in Ruby on Rails

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

问题描述

我正在维护一个 Ruby on Rails 应用程序,并且正在寻找一种简单的方法来查找我所在机器的主机名或 IP 地址(因为它是一个虚拟机,新实例可能具有不同的主机名或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?

下面的答案是正确的,但克雷格提供的说明很有用(另请参阅答案中提供的链接):

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

[下面] 的代码不会使连接或发送任何数据包(到64.233.187.99 这是谷歌).由于 UDP 是无状态协议 connect()只是进行系统调用弄清楚如何路由数据包基于地址和什么接口(以及 IP 地址)它应该绑定到.addr() 返回一个包含家族 (AF_INET) 的数组,本地端口和本地地址(其中是我们想要的)套接字.

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.

推荐答案

来自 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆