The sum of two network masks in ruby

Viewed 54

Amazon now owns 3.0.0.0/8 Apparently bought in two chunks: 3.0.0.0/9 and 3.128.0.0/9.

How do I write program in Ruby to add 3.0.0.0/9 and 3.128.0.0/9 and get result - 3.0.0.0/8?

I can convert mask to cidr this way:

"255.255.255.0"  \
    .split(".") \
    .map { |e| e.to_i.to_s(2).rjust(8, "0") } \
    .join \
    .count("1") # => 24

But how can I add one mask to another?

This is what I have now:

[1] pry(main)> "3.128.0.0".split('.').map { |e| e.to_i.to_s(2).rjust(8, "0") }
=> ["00000011", "10000000", "00000000", "00000000"]
[2] pry(main)> "3.0.0.0".split('.').map { |e| e.to_i.to_s(2).rjust(8, "0") }
=> ["00000011", "00000000", "00000000", "00000000"]

How do I apply /9 to both of addresses above?

1 Answers

I don't know if I properly get the point, but maybe this can help.

Defining some methods to do calculations:

def ip_to_bin(ip)
  ip.split('.').map { |e| e.to_i.to_s(2).rjust(8, "0").split('').map(&:to_i) }
end

def network(ip, mask)
  # convert string to array of bin
  ip = ip_to_bin(ip)
  mask = ip_to_bin(mask)
  # then bitwise sums
  ip.zip(mask).map { |e| e.first.zip(e.last).map { |s, a| s & a } }.map { |e| e.reverse.map.with_index { |d,i| d.to_i * 2**i }.sum }.join('.')
end

def cidr_to_mask(cidr)
  (cidr.times.map{ 1 } + (32 - cidr).times.map{ 0 }).each_slice(8).map { |e| e.reverse.map.with_index { |d,i| d.to_i * 2**i }.sum }.join('.')
end

Then calculate your network using the methods:

cidr = 8
ip = "3.0.0.0"
mask = cidr_to_mask(cidr) #=> "255.0.0.0"
network(ip, mask) #=> "3.0.0.0"

Another example:

network("176.232.53.237", cidr_to_mask(26)) #=> "176.232.53.192"

To calculate the number of hosts from CIDR:

def nr_hosts_from(cidr)
  ((32-cidr).times.map{ 1 }).reverse.map.with_index { |d,i| d.to_i * 2**i }.sum - 1
end

nr_hosts_from(8) #=> 16777214
nr_hosts_from(9) #=>  8388606
Related