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

时间:2021-08-27 23:32:21

I am doing Rails development in Ubuntu 12.04LTS OS.

我正在Ubuntu 12.04LTS操作系统中进行Rails开发。

I want to capture my local IP address in a file, not the loopback 127.0.0.1, the one which I get using ifconfig. Please suggest a solution.

我想在一个文件中捕获本地IP地址,而不是我使用ifconfig的环回127.0.0.1。请建议一个解决方案。

3 个解决方案

#1


23  

Use Socket::ip_address_list.

使用套接字::ip_address_list。

Socket.ip_address_list #=> Array of AddrInfo

#2


2  

Write below method

编写下面的方法

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

and then call local_ip method, you will get ip address of your machine.

然后调用local_ip方法,您将获得计算机的ip地址。

Eg: ip_address= local_ip

#3


2  

This is my first way:

这是我的第一个方法:

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"

This is my second way, which is not recommended:

这是我的第二种方式,不推荐:

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

The third way:

第三种方法:

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

And a fourth way:

第四种方法:

Use Socket#ip_address_list

Socket.ip_address_list #=> Array of AddrInfo

#1


23  

Use Socket::ip_address_list.

使用套接字::ip_address_list。

Socket.ip_address_list #=> Array of AddrInfo

#2


2  

Write below method

编写下面的方法

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

and then call local_ip method, you will get ip address of your machine.

然后调用local_ip方法,您将获得计算机的ip地址。

Eg: ip_address= local_ip

#3


2  

This is my first way:

这是我的第一个方法:

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"

This is my second way, which is not recommended:

这是我的第二种方式,不推荐:

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

The third way:

第三种方法:

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

And a fourth way:

第四种方法:

Use Socket#ip_address_list

Socket.ip_address_list #=> Array of AddrInfo