我需要获取我的IP (即DHCP)。我在我的environment.rb中使用了这个
LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost"但是有没有rubyway或者更干净的解决方案呢?
发布于 2011-10-18 22:55:02
服务器通常有多个接口,至少一个私有接口和一个公共接口。
因为这里的所有答案都处理这个简单的场景,所以更简洁的方法是向套接字询问当前的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方法,您可以轻松地找到更适合您的情况的解决方案。
发布于 2011-02-17 21:58:16
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。
发布于 2011-02-17 22:19:46
这是对steenslag的解决方案的一个小修改
require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}https://stackoverflow.com/questions/5029427
复制相似问题