helper: add ipaddr pkg to check for any IP addresses.

This commit is contained in:
James Rasell
2022-03-03 11:24:50 +01:00
parent d22a3ddc7e
commit 13da88bc74
2 changed files with 63 additions and 0 deletions

10
helper/ipaddr/ipaddr.go Normal file
View File

@@ -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 == "[::]" }

View File

@@ -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))
})
}
}