goipgrep: refactor into module; pure-Go ping/resolve; cache+CI; drop binary
This commit is contained in:
27
projects/go-tools/go/goipgrep/internal/normalize/ip.go
Normal file
27
projects/go-tools/go/goipgrep/internal/normalize/ip.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package normalize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// NormalizeIP validates an IP string and returns a canonical string form.
|
||||
// If allowIPv6 is false, only IPv4 is accepted.
|
||||
func NormalizeIP(s string, allowIPv6 bool) (string, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return "", false
|
||||
}
|
||||
ip := net.ParseIP(s)
|
||||
if ip == nil {
|
||||
return "", false
|
||||
}
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
return fmt.Sprintf("%d.%d.%d.%d", v4[0], v4[1], v4[2], v4[3]), true
|
||||
}
|
||||
if !allowIPv6 {
|
||||
return "", false
|
||||
}
|
||||
return ip.String(), true
|
||||
}
|
||||
Reference in New Issue
Block a user