class IPAddress::Prefix32

Constants

IN4MASK

Public Class Methods

new(num) click to toggle source

Creates a new prefix object for 32 bits IPv4 addresses

prefix = IPAddress::Prefix32.new 24
  #=> 24
Calls superclass method IPAddress::Prefix::new
# File lib/ipaddress_2/prefix.rb, line 114
def initialize(num)
  unless (0..32).include? num
    raise ArgumentError, "Prefix must be in range 0..32, got: #{num}"
  end
  super(num)
end
parse_netmask(netmask) click to toggle source

Creates a new prefix by parsing a netmask in dotted decimal form

prefix = IPAddress::Prefix32::parse_netmask "255.255.255.0"
  #=> 24
# File lib/ipaddress_2/prefix.rb, line 220
def self.parse_netmask(netmask)
  octets = netmask.split(".").map{|i| i.to_i}
  num = octets.pack("C"*octets.size).unpack("B*").first.count "1"
  return self.new(num)
end

Public Instance Methods

[](index) click to toggle source

Shortcut for the octecs in the dotted decimal representation

prefix = IPAddress::Prefix32.new 24

prefix[2]
  #=> 255
# File lib/ipaddress_2/prefix.rb, line 195
def [](index)
  octets[index]
end
bits() click to toggle source

Transforms the prefix into a string of bits representing the netmask

prefix = IPAddress::Prefix32.new 24

prefix.bits 
  #=> "11111111111111111111111100000000"
# File lib/ipaddress_2/prefix.rb, line 143
def bits
  "%.32b" % to_u32
end
host_prefix() click to toggle source

Returns the length of the host portion of a netmask.

prefix = Prefix32.new 24

prefix.host_prefix
  #=> 8
# File lib/ipaddress_2/prefix.rb, line 130
def host_prefix
  32 - @prefix
end
hostmask() click to toggle source

The hostmask is the contrary of the subnet mask, as it shows the bits that can change within the hosts

prefix = IPAddress::Prefix32.new 24

prefix.hostmask
  #=> "0.0.0.255"
# File lib/ipaddress_2/prefix.rb, line 209
def hostmask
  [~to_u32].pack("N").unpack("CCCC").join(".")
end
octets() click to toggle source

An array of octets of the IPv4 dotted decimal format

prefix = IPAddress::Prefix32.new 24

prefix.octets
  #=> [255, 255, 255, 0]
# File lib/ipaddress_2/prefix.rb, line 169
def octets
  to_ip.split(".").map{|i| i.to_i}
end
to_ip() click to toggle source

Gives the prefix in IPv4 dotted decimal format, i.e. the canonical netmask we're all used to

prefix = IPAddress::Prefix32.new 24

prefix.to_ip
  #=> "255.255.255.0"
# File lib/ipaddress_2/prefix.rb, line 156
def to_ip
  [bits].pack("B*").unpack("CCCC").join(".")
end
to_u32() click to toggle source

Unsigned 32 bits decimal number representing the prefix

prefix = IPAddress::Prefix32.new 24

prefix.to_u32
  #=> 4294967040
# File lib/ipaddress_2/prefix.rb, line 182
def to_u32
  (IN4MASK >> host_prefix) << host_prefix
end