Class: IpAddress

Inherits:
Object
  • Object
show all
Defined in:
lib/skytap/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.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/skytap/ip_address.rb', line 19

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:



13
14
15
16
# File 'lib/skytap/ip_address.rb', line 13

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:



7
8
9
10
11
12
# File 'lib/skytap/ip_address.rb', line 7

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



55
56
57
# File 'lib/skytap/ip_address.rb', line 55

def inverse
  MAX_IP4 - self
end

#succObject



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

def succ
  self + 1
end

#to_iObject



31
32
33
# File 'lib/skytap/ip_address.rb', line 31

def to_i
  @i
end

#to_sObject



35
36
37
# File 'lib/skytap/ip_address.rb', line 35

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