ruby 将ip长度换算成掩码
求ruby 将ip长度换算成掩码?
比如:41.58.0.0 - 41.58.255.255 65536
将65536 分别换算成255.255.0.0/16
不会ruby ,请帮助谢谢!
皇家蛋黄酱
10 years, 2 months ago
Answers
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
测试:
irb(main):001:0> mask("41.58.0.0", "41.58.255.255")
=> "255.255.0.0/16"
妹特思棒慰
answered 10 years, 2 months ago