From 5cd95b684f8454b4631c320d8c16803c84179716 Mon Sep 17 00:00:00 2001 From: Chris Roberts Date: Wed, 22 Mar 2017 16:31:46 -0700 Subject: [PATCH] Use 127.0.0.1 for host IP when unset and 0.0.0.0 is not available --- .../handle_forwarded_port_collisions.rb | 17 ++++++++++--- .../handle_forwarded_port_collisions_test.rb | 25 +++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb b/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb index 6bd24bbac..1fff8b6a1 100644 --- a/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb +++ b/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb @@ -243,10 +243,19 @@ module Vagrant end def port_check(host_ip, host_port) - # If the user hasn't specified a host_ip, his/her intention is taken to be - # to listen on all interfaces. - return is_port_open?("0.0.0.0", host_port) if host_ip.nil? - return is_port_open?(host_ip, host_port) + # If no host_ip is specified, intention taken to be list on all interfaces. + # If platform is windows, default back to localhost only + test_host_ip = host_ip || "0.0.0.0" + begin + is_port_open?(test_host_ip, host_port) + rescue Errno::EADDRNOTAVAIL + if !host_ip && test_host_ip == "0.0.0.0" + test_host_ip = "127.0.0.1" + retry + else + raise + end + end end def with_forwarded_ports(env) diff --git a/test/unit/vagrant/action/builtin/handle_forwarded_port_collisions_test.rb b/test/unit/vagrant/action/builtin/handle_forwarded_port_collisions_test.rb index 8ffb08339..7cb34f860 100644 --- a/test/unit/vagrant/action/builtin/handle_forwarded_port_collisions_test.rb +++ b/test/unit/vagrant/action/builtin/handle_forwarded_port_collisions_test.rb @@ -106,4 +106,29 @@ describe Vagrant::Action::Builtin::HandleForwardedPortCollisions do describe "#recover" do end + + describe "#port_check" do + let(:host_ip){ "127.0.0.1" } + let(:host_port){ 8080 } + + it "should check if the port is open" do + expect(instance).to receive(:is_port_open?).with(host_ip, host_port).and_return true + instance.send(:port_check, host_ip, host_port) + end + + context "when host_ip is not set" do + let(:host_ip){ nil } + + it "should set host_ip to 0.0.0.0 when unset" do + expect(instance).to receive(:is_port_open?).with("0.0.0.0", host_port).and_return true + instance.send(:port_check, host_ip, host_port) + end + + it "should set host_ip to 127.0.0.1 when 0.0.0.0 is not available" do + expect(instance).to receive(:is_port_open?).with("0.0.0.0", host_port).and_raise Errno::EADDRNOTAVAIL + expect(instance).to receive(:is_port_open?).with("127.0.0.1", host_port).and_return true + instance.send(:port_check, host_ip, host_port) + end + end + end end