feat(netutil): add local and private host detection helper

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-08 16:17:20 +08:00
parent 0eed208bbf
commit 13fdf464ae
2 changed files with 65 additions and 0 deletions
@@ -0,0 +1,32 @@
package netutil
import (
"net"
"strings"
)
func IsLocalOrPrivateHost(host string) bool {
host = strings.ToLower(strings.TrimSpace(host))
if host == "" {
return false
}
if host == "localhost" || strings.HasSuffix(host, ".localhost") || host == "host.docker.internal" {
return true
}
ip := net.ParseIP(host)
return ip != nil && IsLocalOrPrivateIP(ip)
}
func IsLocalOrPrivateIP(ip net.IP) bool {
if ip == nil {
return false
}
if ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
return true
}
ip4 := ip.To4()
if ip4 == nil {
return false
}
return ip4[0] == 100 && ip4[1] >= 64 && ip4[1] <= 127
}