Count IP addresses

我是研究僧i 提交于 2019-12-13 09:28:09

问题


I stored the following IPs in an array:

10.2.3.1
10.2.3.5
10.2.3.10 - 10.2.3.15

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

Are there any IP address counters?


回答1:


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

That should do it.




回答2:


It makes perfect sense to use the IPAddr class, as @tadman did, but it should be noted that the methods in that class are not doing anything very special. @tadman's answer works just fine if his method ip (the only one to use an IPAddr method) is replaced with:

def ip(str)
  str.split('.').map { |s| s.to_i.to_s(2).rjust(8,'0') }.join.to_i(2)
end

Let's compare:

require 'ipaddr'

def tadip(string)
  IPAddr.new(string).to_i
end

str = "10.2.3.10"
tadip str #=> 167904010 
ip    str #=> 167904010 

str = "255.255.255.255"
tadip str #=> 4294967295 
ip    str #=> 4294967295 

str = "172.0.254.1"
tadip str #=> 2885746177 
ip    str #=> 2885746177 

In fact, ip, unlike IPAddr::new works for IPv6 (32**2 bits) as well as IPv4 (32 bits) IP's (-:

str = "172.0.254.1.22.33.44.55"
tadip str #=> IPAddr::InvalidAddressError: invalid address
ip    str #=> 12394185455143300151


来源:https://stackoverflow.com/questions/30650295/count-ip-addresses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!