diff --git a/lib/vagrant/util/network_ip.rb b/lib/vagrant/util/network_ip.rb index 5f22f69d4..1a4653656 100644 --- a/lib/vagrant/util/network_ip.rb +++ b/lib/vagrant/util/network_ip.rb @@ -5,34 +5,9 @@ module Vagrant module NetworkIP # Returns the network address of the given IP and subnet. # - # If the IP address is an IPv6 address, subnet should be a prefix - # length such as "64". - # # @return [String] def network_address(ip, subnet) - # If this is an IPv6 address, then just mask it - if subnet.to_s =~ /^\d+$/ - ip = IPAddr.new(ip) - return ip.mask(subnet.to_i).to_s - end - - ip = ip_parts(ip) - netmask = ip_parts(subnet) - - # Bitwise-AND each octet to get the network address - # in octets and join each part with a period to get - # the resulting network address. - ip.map { |part| part & netmask.shift }.join(".") - end - - protected - - # Splits an IP into the four octets and returns each as an - # integer in an array. - # - # @return [Array] - def ip_parts(ip) - ip.split(".").map { |i| i.to_i } + IPAddr.new(ip).mask(subnet).to_s end end end diff --git a/test/unit/vagrant/util/network_ip_test.rb b/test/unit/vagrant/util/network_ip_test.rb index 9d0d09b12..5351f4f9a 100644 --- a/test/unit/vagrant/util/network_ip_test.rb +++ b/test/unit/vagrant/util/network_ip_test.rb @@ -18,6 +18,10 @@ describe Vagrant::Util::NetworkIP do expect(klass.network_address("192.168.2.234", "24")).to eq("192.168.2.0") end + it "calculates it properly with integer submask" do + expect(klass.network_address("192.168.2.234", 24)).to eq("192.168.2.0") + end + it "calculates it properly for IPv6" do expect(klass.network_address("fde4:8dba:82e1::c4", "64")).to eq("fde4:8dba:82e1::") end @@ -25,5 +29,9 @@ describe Vagrant::Util::NetworkIP do it "calculates it properly for IPv6" do expect(klass.network_address("fde4:8dba:82e1::c4", 64)).to eq("fde4:8dba:82e1::") end + + it "calculates it properly for IPv6 for string mask" do + expect(klass.network_address("fde4:8dba:82e1::c4", "ffff:ffff:ffff:ffff::")).to eq("fde4:8dba:82e1::") + end end end