Class: NetSpace::Subnet

Inherits:
Object
  • Object
show all
Defined in:
lib/netspace/subnet.rb

Overview

Class representing an IP subnet. At its core, it’s a base IP and a netmask, both converted to 32-bit integers for fast comparisons.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ip, bits) ⇒ Subnet

Returns a new instance of Subnet.



12
13
14
15
16
17
18
# File 'lib/netspace/subnet.rb', line 12

def initialize(ip, bits)
  @ip     = ip
  @bits   = bits
  @ip32   = NetSpace::ip2num(ip)
  @mask32 = ~(2 ** (32 - @bits) - 1)
  @mask   = NetSpace::num2ip(@mask32)
end

Instance Attribute Details

#bitsObject

Returns the value of attribute bits.



10
11
12
# File 'lib/netspace/subnet.rb', line 10

def bits
  @bits
end

#ipObject

Returns the value of attribute ip.



10
11
12
# File 'lib/netspace/subnet.rb', line 10

def ip
  @ip
end

#ip32Object

Returns the value of attribute ip32.



10
11
12
# File 'lib/netspace/subnet.rb', line 10

def ip32
  @ip32
end

#maskObject

Returns the value of attribute mask.



10
11
12
# File 'lib/netspace/subnet.rb', line 10

def mask
  @mask
end

#mask32Object

Returns the value of attribute mask32.



10
11
12
# File 'lib/netspace/subnet.rb', line 10

def mask32
  @mask32
end

Instance Method Details

#in?(ip) ⇒ Boolean

Test if indicated IP address resides within the boundaries of the subnet.

Returns:

  • (Boolean)


25
26
27
# File 'lib/netspace/subnet.rb', line 25

def in?(ip)
  return NetSpace::ip2num(ip) & @mask32 == @ip32
end

#ipsObject

Return a list of all IPs (as strings) that are legitimately members of the subnet.



34
35
36
37
38
39
40
41
42
# File 'lib/netspace/subnet.rb', line 34

def ips
  is = []
  ip = @ip32
  while ip & @mask32 == @ip32
    is << NetSpace::num2ip(ip)
    ip += 1
  end
  return is
end