2011-02-17 82 views
14

我需要獲取我的IP(即DHCP)。我在environment.rb使用:Ruby:獲取本地IP(nix)

LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost" 

但有rubyway或更多個清潔解決方案嗎?

+0

可能有多個本地IP地址。通常,通過配置文件指定要使用的地址(例如打開監聽套接字)。 – Thomas 2011-02-17 13:24:30

+0

我需要wlan0 inet地址。我通過我的無線路由器通過DHCP獲取它。因此,對於我的開發環境,我需要在每次重新連接到路由器時設置新的IP。所以現在我想從系統中獲取它。我使用unix命令來獲得它,它工作正常,但現在我正在尋找更多rubyway解決方案。 – fl00r 2011-02-17 13:34:37

+0

可能的重複:http://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails – steenslag 2011-02-17 14:00:58

回答

29

服務器通常具有一個以上的接口,至少一個私有和一個公有的一個小的修改。

由於所有的答案,在這裏用這個簡單的情景應對,更清潔的方法是問插槽當前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中的方法。

11
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

7

這裏是steenslag的溶液

require "socket" 
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}