Ruby: get local IP (nix)

2019-01-17 01:38发布

I need to get my IP (that is DHCP). I use this in my environment.rb:

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

But is there rubyway or more clean solution?

标签: ruby unix ip
3条回答
做自己的国王
2楼-- · 2019-01-17 02:02
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

Found here.

查看更多
等我变得足够好
3楼-- · 2019-01-17 02:16

A server typically has more than one interface, at least one private and one public.

Since all the answers here deal with this simple scenario, a cleaner way is to ask Socket for the current ip_address_list() as in:

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

Both returns an Addrinfo object, so if you need a string you can use the ip_address() method, as in:

ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?

You can easily work out the more suitable solution to your case changing Addrinfo methods used to filter the required interface address.

查看更多
相关推荐>>
4楼-- · 2019-01-17 02:19

Here is a small modification of steenslag's solution

require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}
查看更多
登录 后发表回答