如何在Ruby中获取本地机器的IP地址?

时间:2012-12-24 09:06:57

标签: ruby ip-address

我正在Ubuntu 12.04LTS OS中进行Rails开发。

我想在文件中捕获我的本地IP地址,而不是使用ifconfig获取的回送127.0.0.1。请提出解决方案。

3 个答案:

答案 0 :(得分:24)

使用Socket::ip_address_list

Socket.ip_address_list #=> Array of AddrInfo

答案 1 :(得分:3)

这是我的第一种方式:

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
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

# irb:0> local_ip
# => "192.168.0.127"

这是我的第二种方式,不建议这样做:

require 'socket'
 Socket::getaddrinfo(Socket.gethostname,”echo”,Socket::AF_INET)[0][3]

第三种方式:

 UDPSocket.open {|s| s.connect('64.233.187.99', 1); s.addr.last }

第四种方式:

Use Socket#ip_address_list

Socket.ip_address_list #=> Array of AddrInfo

答案 2 :(得分:2)

写下面的方法

def self.local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
    UDPSocket.open do |s|
      s.connect '64.233.187.99', 1
      s.addr.last
    end
    ensure
      Socket.do_not_reverse_lookup = orig
 end

然后调用local_ip方法,您将获得您机器的IP地址。

Eg: ip_address= local_ip