Modify LoopbackHostPort() so it returns an IPv6 Loopback address when given [::] address

Currently when LoopbackHostPort() is called with 0.0.0.0 and [::] it returns the first loopback
address returned from net.InterfaceAddrs() which is typically 127.0.0.1 (golang does not
specify an order that interfaces are returned). It would be more appropriate if when calling
LoopbackHostPort() with [::] that an IPv6 loopback address is returned, this prevents some cert.
generation failures.
This commit is contained in:
Jacob Tanenbaum 2018-05-22 11:03:47 -04:00
parent 080739a12a
commit 14a03dd646
2 changed files with 6 additions and 3 deletions

View File

@ -63,6 +63,8 @@ func LoopbackHostPort(bindAddress string) (string, string, error) {
return "", "", fmt.Errorf("invalid server bind address: %q", bindAddress)
}
isIPv6 := net.ParseIP(host).To4() == nil
// Value is expected to be an IP or DNS name, not "0.0.0.0".
if host == "0.0.0.0" || host == "::" {
host = "localhost"
@ -72,7 +74,7 @@ func LoopbackHostPort(bindAddress string) (string, string, error) {
addrs, err := net.InterfaceAddrs()
if err == nil {
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && ipnet.IP.IsLoopback() {
if ipnet, ok := address.(*net.IPNet); ok && ipnet.IP.IsLoopback() && isIPv6 == (ipnet.IP.To4() == nil) {
host = ipnet.IP.String()
break
}

View File

@ -59,9 +59,10 @@ func TestLoopbackHostPort(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
t.Fatalf("expected host to be loopback, got %q", host)
if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() || ip.To4() != nil {
t.Fatalf("expected IPv6 host to be loopback, got %q", host)
}
if port != "443" {
t.Fatalf("expected 443 as port, got %q", port)
}