如何在Ruby中获取本地机器的IP地址?
我在Ubuntu 12.04LTS操作系统中进行Rails开发。
我想在一个文件中捕获我的本地IP地址,而不是使用ifconfig
获取的回送127.0.0.1。 请提出解决方案。
使用Socket :: ip_address_list 。
Socket.ip_address_list #=> Array of AddrInfo
写下面的方法
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
这是我的第一种方式:
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