Class: IPAddr4

Inherits:
IPAddr
  • Object
show all
Defined in:
lib/scriptroute/ipaddr4.rb

Overview

require ‘my-ipaddr’

Instance Method Summary collapse

Constructor Details

#initialize(addr) ⇒ IPAddr4

Returns a new instance of IPAddr4.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/scriptroute/ipaddr4.rb', line 13

def initialize(addr)
  @family = Socket::AF_INET
  if( addr.kind_of?(String) ) then
    prefix, len = addr.split('/')
    @addr = in_addr(prefix)
    if(len) then
      mask_len!(len.to_i)
    else
      @mask_addr = IN4MASK 
    end
  else
    @addr = addr
    @mask_addr = IN4MASK 
  end
end

Instance Method Details

#==(other) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/scriptroute/ipaddr4.rb', line 51

def ==(other)
  if other.kind_of?(IPAddr4)
    @addr == other.addr
  else
    @addr == other.to_i # dunno why.
  end
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
# File 'lib/scriptroute/ipaddr4.rb', line 37

def eql?(other)
  if other.kind_of?(IPAddr4) && @family != other.family
    return false
  end
  return (@addr == other.to_i)
end

#hashObject



43
44
45
# File 'lib/scriptroute/ipaddr4.rb', line 43

def hash
  @addr.to_i
end

#in_addr(addr) ⇒ Object

subclass that trusts its initializer and assumes IPv4



6
7
8
9
10
11
12
# File 'lib/scriptroute/ipaddr4.rb', line 6

def in_addr(addr)
  if addr =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
    (($1.to_i << 24) + ($2.to_i << 16) + ($3.to_i << 8) + ($4.to_i))
  else
    nil
  end
end

#include?(other) ⇒ Boolean

faster include method that only works for ipv4.

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
# File 'lib/scriptroute/ipaddr4.rb', line 29

def include?(other)
  if other.kind_of?(IPAddr)
    other_addr = other.to_i
  else # Not IPAddr - assume integer in same family as us
    other_addr   = other.to_i
  end
  return ((@addr & @mask_addr) == (other_addr & @mask_addr))
end

#to_sObject



46
47
48
49
50
# File 'lib/scriptroute/ipaddr4.rb', line 46

def to_s
  # about twice as fast as the map/join based to_s.
  # appears slightly faster than mask then shift.
  "%d.%d.%d.%d" % [ (@addr >> 24) & 0xff, (@addr >> 16) & 0xff, (@addr >> 8) & 0xff, (0xff&@addr) ]   
end