github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/netutil/addr.go (about)

     1  // Copyright 2014 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package netutil
    12  
    13  import (
    14  	"net"
    15  	"strings"
    16  
    17  	"github.com/cockroachdb/errors"
    18  )
    19  
    20  // SplitHostPort is like net.SplitHostPort however it supports
    21  // addresses without a port number. In that case, the provided port
    22  // number is used.
    23  func SplitHostPort(v string, defaultPort string) (addr string, port string, err error) {
    24  	addr, port, err = net.SplitHostPort(v)
    25  	if err != nil {
    26  		var aerr *net.AddrError
    27  		if errors.As(err, &aerr) {
    28  			if strings.HasPrefix(aerr.Err, "too many colons") {
    29  				// Maybe this was an IPv6 address using the deprecated syntax
    30  				// without '[...]'? Try that to help the user with a hint.
    31  				// Note: the following is valid even if defaultPort is empty.
    32  				// (An empty port number is always a valid listen address.)
    33  				maybeAddr := "[" + v + "]:" + defaultPort
    34  				addr, port, err = net.SplitHostPort(maybeAddr)
    35  				if err == nil {
    36  					err = errors.WithHintf(
    37  						errors.Newf("invalid address format: %q", v),
    38  						"enclose IPv6 addresses within [...], e.g. \"[%s]\"", v)
    39  				}
    40  			} else if strings.HasPrefix(aerr.Err, "missing port") {
    41  				// It's inconvenient that SplitHostPort doesn't know how to ignore
    42  				// a missing port number. Oh well.
    43  				addr, port, err = net.SplitHostPort(v + ":" + defaultPort)
    44  			}
    45  		}
    46  	}
    47  	return addr, port, err
    48  }