Skip to content

Commit b03397a

Browse files
author
openset
committed
Add: Validate IP Address
1 parent 7b38580 commit b03397a

File tree

2 files changed

+62
-2
lines changed

2 files changed

+62
-2
lines changed
Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,15 @@
1-
package validate_ip_address
1+
package problem_468
2+
3+
import (
4+
"net"
5+
"regexp"
6+
)
7+
8+
func validIPAddress(IP string) string {
9+
if p4 := net.ParseIP(IP).To4(); len(p4) == net.IPv4len && p4.String() == IP {
10+
return "IPv4"
11+
} else if regexp.MustCompile(`^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$`).MatchString(IP) {
12+
return "IPv6"
13+
}
14+
return "Neither"
15+
}
Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,47 @@
1-
package validate_ip_address
1+
package problem_468
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
expected string
8+
}
9+
10+
func TestValidIPAddress(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: "172.16.254.1",
14+
expected: "IPv4",
15+
},
16+
{
17+
input: "172.16.254.01",
18+
expected: "Neither",
19+
},
20+
{
21+
input: "256.256.256.256",
22+
expected: "Neither",
23+
},
24+
{
25+
input: "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
26+
expected: "IPv6",
27+
},
28+
{
29+
input: "2001:db8:85a3:0:0:8A2E:0370:7334",
30+
expected: "IPv6",
31+
},
32+
{
33+
input: "2001:0db8:85a3::8A2E:0370:7334",
34+
expected: "Neither",
35+
},
36+
{
37+
input: "02001:0db8:85a3:0000:0000:8a2e:0370:7334",
38+
expected: "Neither",
39+
},
40+
}
41+
for _, tc := range tests {
42+
output := validIPAddress(tc.input)
43+
if output != tc.expected {
44+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)