-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip.go
More file actions
43 lines (37 loc) · 1.01 KB
/
ip.go
File metadata and controls
43 lines (37 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package kit
import (
"net"
"strings"
)
// AnonymizeIP drops the last octet of the IPv4 and IPv6 address to anonymize it
func AnonymizeIP(ip string) string {
if ip == "" {
return ""
}
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return ip // not an ip
}
// IPv4
if parsedIP.To4() != nil {
ipParts := strings.Split(parsedIP.String(), ".")
if len(ipParts) == 4 {
ipParts[3] = "0"
return strings.Join(ipParts, ".")
}
}
// IPv6
ipParts := strings.Split(parsedIP.String(), ":")
ipParts[len(ipParts)-1] = "0"
return strings.Join(ipParts, ":")
}
// IsValidIP checks if the given string is a valid IPv4 or IPv6 address by:
// - ensuring the format is correct
// - ensuring the IP is not an unspecified, loopback, private, multicast, or link-local address
func IsValidIP(ipStr string) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
return !ip.IsUnspecified() && !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsMulticast() && !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast()
}