Ruby IP 地址转换方法

zach777 · June 08, 2015 · Last by peter.zhang replied at February 22, 2023 · 1821 hits
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

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

Reply to bastengao

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

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

ip.each do |addr| puts addr end

You need to Sign in before reply, if you don't have an account, please Sign up first.