Maint: rework IPIsPrivate in internal/routing

This commit is contained in:
Quentin McGaw (desktop)
2021-08-23 20:50:50 +00:00
parent 1a677ce4f7
commit 7907146aaf
2 changed files with 100 additions and 20 deletions

View File

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

View File

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