Ruby IP 地址转换方法

zach777 · 2015年06月08日 · 最后由 peter.zhang 回复于 2023年02月22日 · 1821 次阅读
require 'ipaddr'

def ip_to_bin ipaddr
  IPAddr.new(ipaddr).to_i
end

def bin_to_ip binaddr
  [24, 16, 8, 0].collect {|b| (binaddr >> b) & 255}.join('.')
end

def mask_to_masklen mask
  IPAddr.new(mask).to_i.to_s(2).count('1')
end

def masklen_to_mask masklen
  bin_to_ip(((0x1 << (32 - masklen)) - 1) ^ (0x0 - 1))
end

建议用代码块包起来

分享代码不如写个 gem

写的不错啊,虽然没全部看明白原理。但对我来说,直接拿来用,还是不错的。

bastengao 回复

可以使用这个 gem https://github.com/ipaddress-gem/ipaddress

直接循环出这个 IP 内的范围 ip = IPAddress "172.16.10.1/24"

ip.each do |addr| puts addr end

需要 登录 后方可回复, 如果你还没有账号请 注册新账号