host: optimize isPrivateIP (#817)

pull/819/head
Cluas 4 years ago committed by GitHub
parent afd2a6b19a
commit e1b9dd5244
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 34
      internal/host/host.go
  2. 21
      internal/host/host_test.go

@ -5,20 +5,24 @@ import (
"strconv" "strconv"
) )
var (
privateAddrs = []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "fd00::/8"}
)
func isPrivateIP(addr string) bool { func isPrivateIP(addr string) bool {
ipAddr := net.ParseIP(addr) ip := net.ParseIP(addr)
for _, privateAddr := range privateAddrs { if ip4 := ip.To4(); ip4 != nil {
if _, priv, err := net.ParseCIDR(privateAddr); err == nil { // Following RFC 4193, Section 3. Local IPv6 Unicast Addresses which says:
if priv.Contains(ipAddr) { // The Internet Assigned Numbers Authority (IANA) has reserved the
return true // following three blocks of the IPv4 address space for private internets:
} // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
} // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
} // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
return false return ip4[0] == 10 ||
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
(ip4[0] == 192 && ip4[1] == 168)
}
// Following RFC 4193, Section 3. Private Address Space which says:
// The Internet Assigned Numbers Authority (IANA) has reserved the
// following block of the IPv6 address space for local internets:
// FC00:: - FDFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF (FC00::/7 prefix)
return len(ip) == net.IPv6len && ip[0]&0xfe == 0xfc
} }
// Port return a real port. // Port return a real port.
@ -30,8 +34,8 @@ func Port(lis net.Listener) (int, bool) {
} }
// Extract returns a private addr and port. // Extract returns a private addr and port.
func Extract(hostport string, lis net.Listener) (string, error) { func Extract(hostPort string, lis net.Listener) (string, error) {
addr, port, err := net.SplitHostPort(hostport) addr, port, err := net.SplitHostPort(hostPort)
if err != nil { if err != nil {
return "", err return "", err
} }

@ -14,6 +14,27 @@ func TestPrivateIP(t *testing.T) {
{"172.16.0.1", true}, {"172.16.0.1", true},
{"192.168.1.1", true}, {"192.168.1.1", true},
{"8.8.8.8", false}, {"8.8.8.8", false},
{"1.1.1.1", false},
{"9.255.255.255", false},
{"10.0.0.0", true},
{"10.255.255.255", true},
{"11.0.0.0", false},
{"172.15.255.255", false},
{"172.16.0.0", true},
{"172.16.255.255", true},
{"172.23.18.255", true},
{"172.31.255.255", true},
{"172.31.0.0", true},
{"172.32.0.0", false},
{"192.167.255.255", false},
{"192.168.0.0", true},
{"192.168.255.255", true},
{"192.169.0.0", false},
{"fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", false},
{"fc00::", true},
{"fcff:1200:0:44::", true},
{"fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", true},
{"fe00::", false},
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.addr, func(t *testing.T) { t.Run(test.addr, func(t *testing.T) {

Loading…
Cancel
Save