Netmask to CIDR in ruby

前端 未结 7 914
灰色年华
灰色年华 2020-12-29 11:13

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 

into the

7条回答
  •  情话喂你
    2020-12-29 11:48

    Just as a FYI, and to keep the info easily accessible for those who are searching...

    Here's a simple way to convert from CIDR to netmask format:

    def cidr_to_netmask(cidr)
      IPAddr.new('255.255.255.255').mask(cidr).to_s
    end
    

    For instance:

    cidr_to_netmask(24) #=> "255.255.255.0"
    cidr_to_netmask(32) #=> "255.255.255.255"
    cidr_to_netmask(16) #=> "255.255.0.0"
    cidr_to_netmask(22) #=> "255.255.252.0"
    

提交回复
热议问题