ruby 将ip长度换算成掩码
PHP中文网
PHP中文网 2017-04-22 09:00:12
0
1
825

求ruby 将ip长度换算成掩码?
比如:41.58.0.0 - 41.58.255.255 65536
将65536 分别换算成255.255.0.0/16

不会ruby ,请帮助谢谢!

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
大家讲道理
def mask(ip1, ip2)
    num = ->(ip) { n=ip.split("."); n[0].to_i()*0x1000000+n[1].to_i()*0x10000+n[2].to_i()*0x100+n[3].to_i() }
    m=(/(1+)$/.match((num.call(ip1)^num.call(ip2)).to_s(2))[1])
    nip = m.to_i(2)^0xFFFFFFFF
    (nip/0x1000000%0x100).to_s + '.' + (nip/0x10000%0x100).to_s + '.' + (nip/0x100%0x100).to_s + '.' + (nip%0x100).to_s + '/' + m.size.to_s
end

Test:

irb(main):001:0> mask("41.58.0.0", "41.58.255.255")
=> "255.255.0.0/16"
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template