Skip to content

Commit

Permalink
gnet
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Dec 21, 2023
1 parent ac3a748 commit 3df25b1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 19 deletions.
23 changes: 10 additions & 13 deletions util/net/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"io"
"net"
"strings"
"time"

gbytes "github.com/snail007/gmc/util/bytes"
Expand Down Expand Up @@ -269,18 +270,14 @@ func IsPrivateIP(ip string) bool {
if parsedIP == nil {
return false
}
if ip4 := parsedIP.To4(); ip4 != nil {
// Following RFC 1918, Section 3. Private Address Space which says:
// The Internet Assigned Numbers Authority (IANA) has reserved the
// following three blocks of the IP 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 ip4[0] == 10 ||
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
(ip4[0] == 192 && ip4[1] == 168)
if ipv4 := parsedIP.To4(); ipv4 != nil {
// 10.0.0.0/8
// 172.16.0.0/12
// 192.168.0.0/16
return ipv4[0] == 10 || (ipv4[0] == 172 && ipv4[1] >= 16 && ipv4[1] <= 31) || (ipv4[0] == 192 && ipv4[1] == 168)
}
// Following RFC 4193, Section 8. IANA Considerations which says:
// The IANA has assigned the FC00::/7 prefix to "Unique Local Unicast".
return len(ip) == 16 && ip[0]&0xfe == 0xfc
if strings.HasPrefix(ip, "fc00:") || strings.HasPrefix(ip, "fd00:") || strings.HasPrefix(ip, "fe80:") {
return true
}
return false
}
15 changes: 9 additions & 6 deletions util/net/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,20 @@ func TestIsPrivateIP(t *testing.T) {
ip string
expected bool
}{
//private ip
{"192.168.1.1", true},
{"2001:0db8::1", false},
{"8.8.8.8", false},
{"2001:4860:4860::8888", false},
{"invalidIP", false},
{"10.0.0.1", true},
{"172.16.0.1", true},
{"192.168.2.1", true},
{"fc00::1", false},
{"fe80::1", false},
{"fc00::1", true},
{"fe80::1", true},
//public ip
{"2001:0db8::1", false},
{"2001:0db8::2", false},
{"8.8.8.8", false},
{"2001:4860:4860::8888", false},
//invalid ip
{"invalidIP", false},
}

for _, testCase := range testCases {
Expand Down

0 comments on commit 3df25b1

Please sign in to comment.