diff --git a/internal/routing/reader.go b/internal/routing/reader.go index 89bf98f1..fc8ca3e0 100644 --- a/internal/routing/reader.go +++ b/internal/routing/reader.go @@ -265,24 +265,6 @@ func (r *Routing) VPNLocalGatewayIP(vpnIntf string) (ip net.IP, err error) { } func IPIsPrivate(ip net.IP) bool { - if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { - return true - } - privateCIDRBlocks := [8]string{ - "127.0.0.0/8", // localhost - "10.0.0.0/8", // 24-bit block - "172.16.0.0/12", // 20-bit block - "192.168.0.0/16", // 16-bit block - "169.254.0.0/16", // link local address - "::1/128", // localhost IPv6 - "fc00::/7", // unique local address IPv6 - "fe80::/10", // link local address IPv6 - } - for i := range privateCIDRBlocks { - _, CIDR, _ := net.ParseCIDR(privateCIDRBlocks[i]) - if CIDR.Contains(ip) { - return true - } - } - return false + return ip.IsPrivate() || ip.IsLoopback() || + ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() } diff --git a/internal/routing/reader_test.go b/internal/routing/reader_test.go new file mode 100644 index 00000000..1f89d881 --- /dev/null +++ b/internal/routing/reader_test.go @@ -0,0 +1,98 @@ +package routing + +import ( + "net" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_IPIsPrivate(t *testing.T) { + t.Parallel() + + testCases := map[string]struct { + ipString string + isPrivate bool + }{ + "loopback 127.0.0.1": { + ipString: "127.0.0.1", + isPrivate: true, + }, + "loopback 127.0.0.10": { + ipString: "127.0.0.10", + isPrivate: true, + }, + "loopback ::1": { + ipString: "::1", + isPrivate: true, + }, + "private 10.0.0.1": { + ipString: "10.0.0.1", + isPrivate: true, + }, + "private 10.255.255.255": { + ipString: "10.255.255.255", + isPrivate: true, + }, + "private 172.16.0.1": { + ipString: "172.16.0.1", + isPrivate: true, + }, + "private 172.31.255.255": { + ipString: "172.31.255.255", + isPrivate: true, + }, + "private 192.168.0.0": { + ipString: "192.168.0.0", + isPrivate: true, + }, + "private 192.168.255.255": { + ipString: "192.168.255.255", + isPrivate: true, + }, + "private fc00::": { + ipString: "fc00::", + isPrivate: true, + }, + "private fc00::af": { + ipString: "fc00::af", + isPrivate: true, + }, + "local unicast 169.254.0.0": { + ipString: "169.254.0.0", + isPrivate: true, + }, + "local unicast 169.254.255.255": { + ipString: "169.254.255.255", + isPrivate: true, + }, + "local unicast fe80::": { + ipString: "fe80::", + isPrivate: true, + }, + "local unicast fe80::ae": { + ipString: "fe80::ae", + isPrivate: true, + }, + "public IPv4": { + ipString: "11.5.6.7", + }, + "public IPv6": { + ipString: "af6d::", + }, + } + for name, testCase := range testCases { + testCase := testCase + t.Run(name, func(t *testing.T) { + t.Parallel() + + ip := net.ParseIP(testCase.ipString) + require.NotNil(t, ip) + + isPrivate := IPIsPrivate(ip) + + assert.Equal(t, testCase.isPrivate, isPrivate) + }) + } +}