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.



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/vagrant-skytap/util/ip_address.rb', line 44

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:



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

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:



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

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: ~



80
81
82
# File 'lib/vagrant-skytap/util/ip_address.rb', line 80

def inverse
  MAX_IP4 - self
end

#succObject



85
86
87
# File 'lib/vagrant-skytap/util/ip_address.rb', line 85

def succ
  self + 1
end

#to_iObject



56
57
58
# File 'lib/vagrant-skytap/util/ip_address.rb', line 56

def to_i
  @i
end

#to_sObject



60
61
62
# File 'lib/vagrant-skytap/util/ip_address.rb', line 60

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