Method: IPAddress::IPv4#initialize
- Defined in:
- lib/ipaddress/ipv4.rb
#initialize(str) ⇒ IPv4
Creates a new IPv4 address object.
An IPv4 address can be expressed in any of the following forms:
-
“10.1.1.1/24”: ip
addressandprefix. This is the common and
suggested way to create an object .
-
“10.1.1.1/255.255.255.0”: ip
addressandnetmask. Although
convenient sometimes, this format is less clear than the previous one.
-
“10.1.1.1”: if the address alone is specified, the prefix will be
set as default 32, also known as the host prefix
Examples:
# These two are the same
ip = IPAddress::IPv4.new("10.0.0.1/24")
ip = IPAddress("10.0.0.1/24")
# These two are the same
IPAddress::IPv4.new "10.0.0.1/8"
IPAddress::IPv4.new "10.0.0.1/255.0.0.0"
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/ipaddress/ipv4.rb', line 63 def initialize(str) ip, netmask = str.split("/") # Check the ip and remove white space if IPAddress.valid_ipv4?(ip) @address = ip.strip else raise ArgumentError, "Invalid IP #{ip.inspect}" end # Check the netmask if netmask # netmask is defined netmask.strip! if netmask =~ /^\d{1,2}$/ # netmask in cidr format @prefix = Prefix32.new(netmask.to_i) elsif IPAddress.valid_ipv4_netmask?(netmask) # netmask in IP format @prefix = Prefix32.parse_netmask(netmask) else # invalid netmask raise ArgumentError, "Invalid netmask #{netmask}" end else # netmask is nil, reverting to defaul classful mask @prefix = Prefix32.new(32) end # Array formed with the IP octets @octets = @address.split(".").map{|i| i.to_i} # 32 bits interger containing the address @u32 = (@octets[0]<< 24) + (@octets[1]<< 16) + (@octets[2]<< 8) + (@octets[3]) end |