diff --git a/consul/server_test.go b/consul/server_test.go index c86c83f355..380edc4733 100644 --- a/consul/server_test.go +++ b/consul/server_test.go @@ -120,9 +120,10 @@ func TestServer_StartStop(t *testing.T) { config := DefaultConfig() config.DataDir = dir - private, err := GetPrivateIP() + // Advertise on localhost. + private, _, err := net.ParseCIDR("127.0.0.1/32") if err != nil { - t.Fatalf("err: %v", err) + t.Fatalf("failed to parse 127.0.0.1 cidr: %v", err) } config.RPCAdvertise = &net.TCPAddr{ diff --git a/consul/util.go b/consul/util.go index 1be12edc77..a9544c0f21 100644 --- a/consul/util.go +++ b/consul/util.go @@ -169,6 +169,10 @@ func GetPrivateIP() (net.IP, error) { return nil, fmt.Errorf("Failed to get interface addresses: %v", err) } + return getPrivateIP(addresses) +} + +func getPrivateIP(addresses []net.Addr) (net.IP, error) { var candidates []net.IP // Find private IPv4 address @@ -200,6 +204,7 @@ func GetPrivateIP() (net.IP, error) { default: return nil, fmt.Errorf("Multiple private IPs found. Please configure one.") } + } // Converts bytes to an integer diff --git a/consul/util_test.go b/consul/util_test.go index 00b53fe76a..d2f08c397b 100644 --- a/consul/util_test.go +++ b/consul/util_test.go @@ -1,6 +1,7 @@ package consul import ( + "errors" "net" "regexp" "testing" @@ -28,6 +29,74 @@ func TestToLowerList(t *testing.T) { } } +func TestGetPrivateIP(t *testing.T) { + ip, _, err := net.ParseCIDR("10.1.2.3/32") + if err != nil { + t.Fatalf("failed to parse private cidr: %v", err) + } + + pubIP, _, err := net.ParseCIDR("8.8.8.8/32") + if err != nil { + t.Fatalf("failed to parse public cidr: %v", err) + } + + tests := []struct { + addrs []net.Addr + expected net.IP + err error + }{ + { + addrs: []net.Addr{ + &net.IPAddr{ + IP: ip, + }, + &net.IPAddr{ + IP: pubIP, + }, + }, + expected: ip, + }, + { + addrs: []net.Addr{ + &net.IPAddr{ + IP: pubIP, + }, + }, + err: errors.New("No private IP address found"), + }, + { + addrs: []net.Addr{ + &net.IPAddr{ + IP: ip, + }, + &net.IPAddr{ + IP: ip, + }, + &net.IPAddr{ + IP: pubIP, + }, + }, + err: errors.New("Multiple private IPs found. Please configure one."), + }, + } + + for _, test := range tests { + ip, err := getPrivateIP(test.addrs) + switch { + case test.err != nil && err != nil: + if err.Error() != test.err.Error() { + t.Fatalf("unexpected error: %v != %v", test.err, err) + } + case (test.err == nil && err != nil) || (test.err != nil && err == nil): + t.Fatalf("unexpected error: %v != %v", test.err, err) + default: + if !test.expected.Equal(ip) { + t.Fatalf("unexpected ip: %v != %v", ip, test.expected) + } + } + } +} + func TestIsPrivateIP(t *testing.T) { if !isPrivateIP("192.168.1.1") { t.Fatalf("bad")