Class: IPAddr

Inherits:
Object
  • Object
show all
Defined in:
lib/hpc/dns.rb

Overview

override IPAddr class to add prefix method

Instance Method Summary (collapse)

Instance Method Details

Method: IPAddr#prefix

Defined in:
lib/hpc/dns.rb

- (Object) prefix



54
55
56
57
58
59
60
61
# File 'lib/hpc/dns.rb', line 54

def prefix
  if @addr
    # count the number of 1 in binary repr of addr mask
    @mask_addr.to_s(2).count('1')
  else
    nil
  end
end

Method: IPAddr#subnets

Defined in:
lib/hpc/dns.rb

- (Object) subnets



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/hpc/dns.rb', line 63

def subnets
  if prefix < 16
    STDERR.puts "Unable to calc /24 subnets on networks with cidr prefix #{prefix} < 16"
    return []
  elsif prefix >= 24
    return [ self ]
  end

  begin_addr_i = (@addr & @mask_addr)

  case @family
  when Socket::AF_INET
    end_addr_i = (@addr | (IN4MASK ^ @mask_addr))
  when Socket::AF_INET6
    end_addr_i = (@addr | (IN6MASK ^ @mask_addr))
  else
    raise "unsupported address family"
  end

  begin_addr = clone.set(begin_addr_i, @family)
  end_addr = clone.set(end_addr_i, @family)

  # FIXME: Starting from here, the logic really sucks and only works on ipv4
  # networks whose CIDR prefix is between 16 and 24.

  subnets_a = Array.new()

  network_number = begin_addr.to_s.split('.')[0..1]

  first_subnet = begin_addr.to_s.split('.')[2].to_i
  last_subnet  = end_addr.to_s.split('.')[2].to_i

  (first_subnet..last_subnet).each do |subnet_idx|
    subnet_s = [network_number, subnet_idx, '0'].flatten.join('.')
    subnet = IPAddr.new("#{subnet_s}/24")
    subnets_a << subnet
  end

  return subnets_a

end