Class: VagrantPlugins::Skytap::Util::IpAddress

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-skytap/util/ip_address.rb

Defined Under Namespace

Classes: InvalidIp

Constant Summary collapse

IP_REGEX =
/^(0[0-7]*|0[x][0-9a-f]+|[1-9][0-9]*)\.(0[0-7]*|0[x][0-9a-f]+|[1-9][0-9]*)\.(0[0-7]*|0[x][0-9a-f]+|[1-9][0-9]*)\.(0[0-7]*|0[x][0-9a-f]+|[1-9][0-9]*)$/i
MAX_IP4_INT =
2**32 - 1
MAX_IP4 =
self.new(MAX_IP4_INT)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str_or_int) ⇒ IpAddress

Returns a new instance of IpAddress.


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/vagrant-skytap/util/ip_address.rb', line 22

def initialize(str_or_int)
  if str_or_int.is_a?(String)
    @i = self.class.str_to_int(str_or_int)
  elsif str_or_int.is_a?(Integer)
    raise InvalidIp.new("IP #{str_or_int} is greater than the maximum IPv4 value") if str_or_int > MAX_IP4_INT
    raise InvalidIp.new("IP value must be non-negative")  if str_or_int < 0
    @i = str_or_int
  else
    raise InvalidIp.new("Don't know how to make an IP out of #{str_or_int}")
  end
end

Class Method Details

.int_to_str(i) ⇒ Object

Raises:


16
17
18
19
# File 'lib/vagrant-skytap/util/ip_address.rb', line 16

def int_to_str(i)
  raise InvalidIp.new("#{i} exceeds maximum IPv4 address") if i > MAX_IP4_INT
  [24, 16, 8, 0].collect{|shift| (i & (255 << shift)) >> shift}.join('.')
end

.str_to_int(str) ⇒ Object

Raises:


10
11
12
13
14
15
# File 'lib/vagrant-skytap/util/ip_address.rb', line 10

def str_to_int(str)
  raise InvalidIp.new("'#{str}' does not look like an IP") unless str =~ IP_REGEX
  bytes = [Integer($1), Integer($2), Integer($3), Integer($4)]
  raise InvalidIp.new("'#{str}' octet exceeds 255") if bytes.any?{|b| b > 255}
  bytes.zip([24, 16, 8, 0]).collect{|n,shift| n << shift}.inject(&:+)
end

Instance Method Details

#inverseObject Also known as: ~


58
59
60
# File 'lib/vagrant-skytap/util/ip_address.rb', line 58

def inverse
  MAX_IP4 - self
end

#succObject


63
64
65
# File 'lib/vagrant-skytap/util/ip_address.rb', line 63

def succ
  self + 1
end

#to_iObject


34
35
36
# File 'lib/vagrant-skytap/util/ip_address.rb', line 34

def to_i
  @i
end

#to_sObject


38
39
40
# File 'lib/vagrant-skytap/util/ip_address.rb', line 38

def to_s
  self.class.int_to_str(@i)
end