Ruby:如何将 IP 范围转换为 IP 数组

标签 ruby ip

有没有简单的方法可以将 IP 范围转换为 IP 数组?

def convertIPrange (start_ip, end_ip)
 #output: array of ips end
end

例如输入

('192.168.1.105', '192.168.1.108') 

输出

['192.168.1.105','192.158.1.106','192.158.1.107','192.158.1.108']

最佳答案

使用 Ruby 标准库 IPAddr

# I would suggest naming your function using underscore rather than camelcase
# because of Ruby naming conventions
#
require 'ipaddr'

def convert_ip_range(start_ip, end_ip)
  start_ip = IPAddr.new(start_ip)
  end_ip   = IPAddr.new(end_ip)

  # map to_s if you like, you can also call to_a, 
  # IPAddrs have some neat functions regarding IPs, 
  # be sure to check them out
  #
  (start_ip..end_ip).map(&:to_s) 
end

关于Ruby:如何将 IP 范围转换为 IP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20608121/

相关文章:

ruby - 如何在 ruby​​ 中创建平面文件

ruby - 如何在 cucumber 步骤定义之外使用 rspec-expectations

ruby - 如何构建 XML 文件?

networking - 网站无法 ping 通,但可以通过 Web 浏览器打开

c++ - 在 C++ 中获取本地 IP 地址

c++ - 使用 C++ 在 vi​​sual studio 中进行套接字编程

python - 有没有可能为动态语言创建编译器而不失去他的动态特性?

ruby - 如何让 iconv 忽略编码错误?

Android,获取用户ip地址

php - 将 IP 存储为 unsigned int?