diff --git a/helper/ipaddr/ipaddr.go b/helper/ipaddr/ipaddr.go new file mode 100644 index 000000000..e42d41c0b --- /dev/null +++ b/helper/ipaddr/ipaddr.go @@ -0,0 +1,10 @@ +package ipaddr + +// IsAny checks if the given IP address is an IPv4 or IPv6 ANY address. +func IsAny(ip string) bool { + return isAnyV4(ip) || isAnyV6(ip) +} + +func isAnyV4(ip string) bool { return ip == "0.0.0.0" } + +func isAnyV6(ip string) bool { return ip == "::" || ip == "[::]" } diff --git a/helper/ipaddr/ipaddr_test.go b/helper/ipaddr/ipaddr_test.go new file mode 100644 index 000000000..ad64003a0 --- /dev/null +++ b/helper/ipaddr/ipaddr_test.go @@ -0,0 +1,53 @@ +package ipaddr + +import ( + "net" + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_IsAny(t *testing.T) { + testCases := []struct { + inputIP string + expectedOutput bool + name string + }{ + { + inputIP: "0.0.0.0", + expectedOutput: true, + name: "string ipv4 any IP", + }, + { + inputIP: "::", + expectedOutput: true, + name: "string ipv6 any IP", + }, + { + inputIP: net.IPv4zero.String(), + expectedOutput: true, + name: "net.IP ipv4 any", + }, + { + inputIP: net.IPv6zero.String(), + expectedOutput: true, + name: "net.IP ipv6 any", + }, + { + inputIP: "10.10.10.10", + expectedOutput: false, + name: "internal ipv4 address", + }, + { + inputIP: "8.8.8.8", + expectedOutput: false, + name: "public ipv4 address", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.expectedOutput, IsAny(tc.inputIP)) + }) + } +}