-
Notifications
You must be signed in to change notification settings - Fork 3
/
ip.go
executable file
·66 lines (59 loc) · 1.15 KB
/
ip.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package ipKit
import (
"github.com/richelieu-yang/chimera/v2/src/ip/ipKit/ipType"
"net"
)
// GetIpInfo 获取ip字符串的信息.
/*
@param str 字符串,IPv4 或 IPv6
*/
func GetIpInfo(str string) IpInfo {
kind := ipType.UNKNOWN
ip := net.ParseIP(str)
if ip != nil {
// !!!:加入标签才能break 外面的循环
//OuterLoop:
// for _, c := range str {
// switch c {
// case '.':
// kind = ipType.IPv4
// break OuterLoop
// case ':':
// kind = ipType.IPv6
// break OuterLoop
// default:
// break
// }
// }
// If ip is not an IPv4 address, To4 returns nil.
if ip.To4() != nil {
kind = ipType.IPv4
} else {
kind = ipType.IPv6
}
}
return IpInfo{
Type: kind,
IP: ip,
}
}
// IsIP 检查传参是否为ip(支持ipv4和ipv6)?
/*
参考:https://www.php.cn/be/go/441401.html
*/
func IsIP(str string) bool {
return net.ParseIP(str) != nil
}
// IsIPv4
/*
"0.0.0.0" => true
"127.0.0.1" => true
*/
func IsIPv4(str string) bool {
ip := net.ParseIP(str)
return ip != nil && ip.To4() != nil
}
func IsIPv6(str string) bool {
ip := net.ParseIP(str)
return ip != nil && ip.To4() == nil
}