Ruby:获取本地IP(nix)

fl0*_*00r 14 ruby unix ip

我需要获取我的IP(即DHCP).我用我的environment.rb:

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

但有没有rubyway或更清洁的解决方案?

Cla*_*ani 30

服务器通常具有多个接口,至少一个私有接口和一个公共接口.

由于这里的所有答案都涉及这个简单的场景,更简洁的方法是向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
Run Code Online (Sandbox Code Playgroud)

两者都返回一个Addrinfo对象,因此如果您需要一个字符串,您可以使用该ip_address()方法,如:

ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?
Run Code Online (Sandbox Code Playgroud)

您可以轻松地找到更合适的解决方案,以更改用于过滤所需接口地址的Addrinfo方法.

  • 顺便说一句,我认为这在v1.8中不可用 (3认同)

ste*_*lag 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
Run Code Online (Sandbox Code Playgroud)

这里找到.


D-D*_*oug 7

这是对steenslag解决方案的一个小修改

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

  • 为什么这是一个改进?@steenslag运行速度更快,因为它禁用DNS查找,更短的代码并不总是更好 (3认同)