diff --git a/internal/pkg/agent/configuration/grpc.go b/internal/pkg/agent/configuration/grpc.go index 896b4ab3eb9..d7220672079 100644 --- a/internal/pkg/agent/configuration/grpc.go +++ b/internal/pkg/agent/configuration/grpc.go @@ -5,7 +5,7 @@ package configuration import ( - "fmt" + "net" "os" "strconv" @@ -71,7 +71,7 @@ func OverrideDefaultContainerGRPCPort(cfg *GRPCConfig) { // String returns the composed listen address for the GRPC. func (cfg *GRPCConfig) String() string { - return fmt.Sprintf("%s:%d", cfg.Address, cfg.Port) + return net.JoinHostPort(cfg.Address, strconv.Itoa(int(cfg.Port))) } // IsLocal returns true if port value is less than 0 diff --git a/internal/pkg/agent/configuration/grpc_test.go b/internal/pkg/agent/configuration/grpc_test.go index 65d02ad4644..27043e277e3 100644 --- a/internal/pkg/agent/configuration/grpc_test.go +++ b/internal/pkg/agent/configuration/grpc_test.go @@ -42,3 +42,40 @@ func TestOverrideDefaultGRPCPort(t *testing.T) { }) } } + +func TestGRPCAddr(t *testing.T) { + testcases := []struct { + name string + addr string + port uint16 + expected string + }{{ + name: "ipv4", + addr: "127.0.0.1", + expected: "127.0.0.1:0", + }, { + name: "ipv4+port", + addr: "127.0.0.1", + port: 1, + expected: "127.0.0.1:1", + }, { + name: "ipv6", + addr: "::1", + expected: "[::1]:0", + }, { + name: "ipv6+port", + addr: "::1", + port: 1, + expected: "[::1]:1", + }} + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + cfg := GRPCConfig{ + Address: tc.addr, + Port: tc.port, + } + assert.Equal(t, tc.expected, cfg.String()) + }) + } +} diff --git a/pkg/component/runtime/manager.go b/pkg/component/runtime/manager.go index 5ee8b5b4681..623d0e58df1 100644 --- a/pkg/component/runtime/manager.go +++ b/pkg/component/runtime/manager.go @@ -14,6 +14,7 @@ import ( "net" "net/url" "path" + "strconv" "strings" "sync" "time" @@ -988,9 +989,9 @@ func (m *Manager) getListenAddr() string { if m.isLocal { return m.listenAddr } - addr := strings.SplitN(m.listenAddr, ":", 2) - if len(addr) == 2 && addr[1] == "0" { - return fmt.Sprintf("%s:%d", addr[0], m.listenPort) + host, port, err := net.SplitHostPort(m.listenAddr) + if err == nil && port == "0" { + return net.JoinHostPort(host, strconv.Itoa(m.listenPort)) } return m.listenAddr }