Netmask to CIDR in ruby

前端 未结 7 915
灰色年华
灰色年华 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:53

    Here's a more mathematical approach, avoiding strings at all costs:

    def cidr_mask
        Integer(32-Math.log2((IPAddr.new(mask,Socket::AF_INET).to_i^0xffffffff)+1))
    end
    

    with "mask" being a string like 255.255.255.0. You can modify it and change the first argument to just "mask" if "mask" is already an integer representation of an IP address.

    So for example, if mask was "255.255.255.0", IPAddr.new(mask,Socket::AF_INET).to_i would become 0xffffff00, which is then xor'd with 0xffffffff, which equals 255.

    We add 1 to that to make it a complete range of 256 hosts, then find the log base 2 of 256, which equals 8 (the bits used for the host address), then subtract that 8 from 32, which equals 24 (the bits used for the network address).

    We then cast to integer because Math.log2 returns a float.

提交回复
热议问题