我需要获取我的IP(即DHCP)。我在environment.rb
使用:Ruby:获取本地IP(nix)
LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost"
但有rubyway或更多个清洁解决方案吗?
我需要获取我的IP(即DHCP)。我在environment.rb
使用:Ruby:获取本地IP(nix)
LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost"
但有rubyway或更多个清洁解决方案吗?
服务器通常具有一个以上的接口,至少一个私有和一个公有的一个小的修改。
由于所有的答案,在这里用这个简单的情景应对,更清洁的方法是问插槽当前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
找到here。
这里是steenslag的溶液
require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}
可能有多个本地IP地址。通常,通过配置文件指定要使用的地址(例如打开监听套接字)。 – Thomas 2011-02-17 13:24:30
我需要wlan0 inet地址。我通过我的无线路由器通过DHCP获取它。因此,对于我的开发环境,我需要在每次重新连接到路由器时设置新的IP。所以现在我想从系统中获取它。我使用unix命令来获得它,它工作正常,但现在我正在寻找更多rubyway解决方案。 – fl00r 2011-02-17 13:34:37
可能的重复:http://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails – steenslag 2011-02-17 14:00:58