我需要获取我的IP地址(即动态主机配置协议(DHCP)获得的地址)。我在environment.rb
文件中使用以下代码:
LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost"
但是否有更优雅或更简洁的 Ruby 解决方案呢?
我需要获取我的IP地址(即动态主机配置协议(DHCP)获得的地址)。我在environment.rb
文件中使用以下代码:
LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost"
但是否有更优雅或更简洁的 Ruby 解决方案呢?
服务器通常有多个接口,至少有一个私有接口和一个公共接口。
由于所有这里的答案都处理了这个简单的情况,更清晰的方式是像下面这样通过 Socket 请求当前的 ip_address_list()
:
require 'socket'
def my_first_private_ipv4
Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end
def my_first_public_ipv4
Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
end
两者都返回一个Addrinfo
对象,因此如果您需要一个字符串,可以使用ip_address()
方法,例如:
ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?
您可以通过更改Addrinfo方法来过滤所需的接口地址,从而轻松找到更适合您情况的解决方案。
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 #google
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
puts local_ip
从这里找到。
require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}