本文介绍了计数IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在阵列中存储了以下IP:
I stored the following IPs in an array:
10.2.3.1
10.2.3.5
10.2.3.10 - 10.2.3.15
我正在尝试计算IP地址的总数. IP地址的总数应为8.当我遍历数组时,总共得到三个计数.我需要一种计算第三项的方法:
I'm trying to count the total number of IP addresses. The total number of IP addresses should be 8. When I iterate through the array, I get a total of three counts. I need a way to count the third item:
10.2.3.10 - 10.2.3.15
有IP地址计数器吗?
推荐答案
如果需要将IP转换为范围,则需要一个将IPv4值转换为整数的函数,然后对它们进行数学运算: /p>
If you need to convert an IP to a range, you'll need a function that converts an IPv4 value to an integer, then do math on those:
require 'ipaddr'
def ip(string)
IPAddr.new(string).to_i
end
def parse_ip(string)
string.split(/\s+\-\s+/).collect { |v| ip(v) }
end
def ip_range(string)
ips = parse_ip(string)
ips.last - ips.first + 1
end
ip_range("10.2.3.10 - 10.2.3.15")
# => 6
应该这样做.
这篇关于计数IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!