forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate-ip-address.go
executable file
·88 lines (68 loc) · 1.14 KB
/
validate-ip-address.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package problem0468
import (
"strconv"
"strings"
)
func validIPAddress(IP string) string {
switch {
case isIPv4(IP):
return "IPv4"
case isIPv6(IP):
return "IPv6"
default:
return "Neither"
}
}
func isIPv4(IP string) bool {
if !strings.Contains(IP, ".") {
return false
}
ss := strings.Split(IP, ".")
if len(ss) != 4 {
return false
}
for _, s := range ss {
if !isV4Num(s) {
return false
}
}
return true
}
func isV4Num(s string) bool {
if len(s) == 0 {
return false
}
if len(s) > 1 &&
(s[0] < '1' || '9' < s[0]) {
return false
}
n, err := strconv.Atoi(s)
return err == nil && 0 <= n && n < 256
}
func isIPv6(IP string) bool {
if !strings.Contains(IP, ":") {
return false
}
ss := strings.Split(IP, ":")
if len(ss) != 8 {
return false
}
for _, s := range ss {
if !isV6Num(s) {
return false
}
}
return true
}
func isV6Num(s string) bool {
if len(s) == 0 || len(s) > 4 {
return false
}
if !('0' <= s[0] && s[0] <= '9') &&
!('a' <= s[0] && s[0] <= 'z') &&
!('A' <= s[0] && s[0] <= 'Z') {
return false
}
n, err := strconv.ParseInt(s, 16, 64)
return err == nil && 0 <= n && n < 1<<16
}