diff --git a/caddy.go b/caddy.go index 415c59cff..39a3358ec 100644 --- a/caddy.go +++ b/caddy.go @@ -232,7 +232,7 @@ func HasListenerWithAddress(addr string) bool { func listenerAddrEqual(ln net.Listener, addr string) bool { lnAddr := ln.Addr().String() hostname, port, err := net.SplitHostPort(addr) - if err != nil || hostname != "" { + if err != nil { return lnAddr == addr } if lnAddr == net.JoinHostPort("::", port) { @@ -241,7 +241,7 @@ func listenerAddrEqual(ln net.Listener, addr string) bool { if lnAddr == net.JoinHostPort("0.0.0.0", port) { return true } - return false + return hostname != "" && lnAddr == addr } // TCPServer is a type that can listen and serve connections. diff --git a/caddy_test.go b/caddy_test.go index 51e93c8ac..bbb93090f 100644 --- a/caddy_test.go +++ b/caddy_test.go @@ -1,6 +1,10 @@ package caddy -import "testing" +import ( + "net" + "strconv" + "testing" +) /* // TODO @@ -56,3 +60,39 @@ func TestIsLoopback(t *testing.T) { } } } + +func TestListenerAddrEqual(t *testing.T) { + ln1, err := net.Listen("tcp", "[::]:0") + if err != nil { + t.Fatal(err) + } + defer ln1.Close() + + ln1port := strconv.Itoa(ln1.Addr().(*net.TCPAddr).Port) + + ln2, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln2.Close() + + ln2port := strconv.Itoa(ln2.Addr().(*net.TCPAddr).Port) + + for i, test := range []struct { + ln net.Listener + addr string + expect bool + }{ + {ln1, ":1234", false}, + {ln1, "0.0.0.0:1234", false}, + {ln1, ":" + ln1port + "", true}, + {ln1, "0.0.0.0:" + ln1port + "", true}, + {ln2, "127.0.0.1:1234", false}, + {ln2, ":" + ln2port + "", false}, + {ln2, "127.0.0.1:" + ln2port + "", true}, + } { + if got, want := listenerAddrEqual(test.ln, test.addr), test.expect; got != want { + t.Errorf("Test %d (%s == %s): expected %v but was %v", i, test.addr, test.ln.Addr().String(), want, got) + } + } +}