diff --git a/pkg/util/funcutil/func.go b/pkg/util/funcutil/func.go index b1b2882c53e3a..02a547c5a91a1 100644 --- a/pkg/util/funcutil/func.go +++ b/pkg/util/funcutil/func.go @@ -57,6 +57,18 @@ func GetIP(ip string) string { if len(ip) == 0 { return GetLocalIP() } + netIP := net.ParseIP(ip) + // not a valid ip addr + if netIP == nil { + panic(errors.Newf(`"%s" in param table is not a valid IP address`, ip)) + } + // only localhost or unicast is acceptable + if netIP.IsUnspecified() { + panic(errors.Newf(`"%s" in param table is Unspecified IP address and cannot be used`)) + } + if netIP.IsMulticast() || netIP.IsLinkLocalMulticast() || netIP.IsInterfaceLocalMulticast() { + panic(errors.Newf(`"%s" in param table is Multicast IP address and cannot be used`)) + } return ip } diff --git a/pkg/util/funcutil/func_test.go b/pkg/util/funcutil/func_test.go index aec82cdcc5817..8333d84f08507 100644 --- a/pkg/util/funcutil/func_test.go +++ b/pkg/util/funcutil/func_test.go @@ -91,11 +91,32 @@ func Test_GetLocalIP(t *testing.T) { } func Test_GetIP(t *testing.T) { - ip := GetIP("") - assert.NotNil(t, ip) - assert.NotZero(t, len(ip)) - ip = GetIP("127.0.0") - assert.Equal(t, ip, "127.0.0") + t.Run("empty_fallback_auto", func(t *testing.T) { + ip := GetIP("") + assert.NotNil(t, ip) + assert.NotZero(t, len(ip)) + }) + + t.Run("valid_ip", func(t *testing.T) { + assert.NotPanics(t, func() { + ip := GetIP("8.8.8.8") + assert.Equal(t, "8.8.8.8", ip) + }) + }) + + t.Run("invalid_ip", func(t *testing.T) { + assert.Panics(t, func() { + GetIP("null") + }, "null is invalid ip address, panicking") + + assert.Panics(t, func() { + GetIP("0.0.0.0") + }, "null is unspecified ip address, panicking") + + assert.Panics(t, func() { + GetIP("224.0.0.1") + }, "null is multicast ip address, panicking") + }) } func Test_ParseIndexParamsMap(t *testing.T) {