Ruby:获取本地IP(nix) [英] Ruby: get local IP (nix)

查看:419
本文介绍了Ruby:获取本地IP(nix)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取我的IP(即DHCP)。我在 environment.rb 中使用它:

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"

但是还有rubyway还是更干净的解决方案?

But is there rubyway or more clean solution?

推荐答案

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

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

全部这里的答案处理这个简单的场景,更简洁的方法是向Socket询问当前的 ip_address_list(),如下所示:

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

两者都返回 Addrinfo object,所以如果你需要一个字符串,你可以使用 ip_address()方法,如:

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?

您可以轻松找到更合适的解决方案来更改用于过滤所需界面的Addrinfo方法地址。

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

这篇关于Ruby:获取本地IP(nix)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆