红宝石中的网络掩码到CIDR [英] Netmask to CIDR in ruby

查看:181
本文介绍了红宝石中的网络掩码到CIDR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用ip-address gem,它似乎没有能力转换形式的网络掩码

I've been using the ip-address gem and it doesn't seem to have the ability to convert from a netmask of the form

255.255.255.0 

进入CIDR表格

/24

有没有人有想法如何快速将前者转换为后者?

Does anyone have an ideas how to quickly convert the former to the latter ?

推荐答案

以下是快速而肮脏的方式

Here is the quick and dirty way

require 'ipaddr'
puts IPAddr.new("255.255.255.0").to_i.to_s(2).count("1")

应该有适当的功能,我找不到,所以我只算1

There should be proper function for that, I couldn't find that, so I just count "1"

如果你打算在很多地方使用这个功能而不介意monkeypatching,这可能会有所帮助:

If you're going to be using the function in a number of places and don't mind monkeypatching, this could help:

IPAddr.class_eval
  def to_cidr
    "/" + self.to_i.to_s(2).count("1")
  end
end

然后你得到

IPAddr.new('255.255.255.0').to_cidr
# => "/24"

这篇关于红宝石中的网络掩码到CIDR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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