-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
89 lines (85 loc) · 1.63 KB
/
solution.js
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
89
/**
* @param {string} IP
* @return {string}
*/
const numMap = {
0: true,
1: true,
2: true,
3: true,
4: true,
5: true,
6: true,
7: true,
8: true,
9: true,
};
function isIPv4 (IP) {
const arr = IP.split('.');
if (arr.length !== 4) {
return false;
}
for (let i = 0; i < 4; i++) {
if (arr[i].length < 1 || arr[i].length > 3 || (arr[i].length > 1 && arr[i][0] === '0')) {
return false;
}
for (let j = 0; j < arr[i].length; j++) {
if (numMap[arr[i][j]] === undefined) {
return false;
}
}
if (+arr[i] > 255) {
return false;
}
}
return true;
}
const map = {
0: true,
1: true,
2: true,
3: true,
4: true,
5: true,
6: true,
7: true,
8: true,
9: true,
a: true,
A: true,
b: true,
B: true,
c: true,
C: true,
d: true,
D: true,
e: true,
E: true,
f: true,
F: true,
};
function isIPv6 (IP) {
const arr = IP.split(':');
if (arr.length !== 8) {
return false;
}
for (let i = 0; i < 8; i++) {
if (arr[i].length < 1 || arr[i].length > 4) {
return false;
}
for (let j = 0; j < arr[i].length; j++) {
if (map[arr[i][j]] === undefined) {
return false;
}
}
}
return true;
}
var validIPAddress = function (IP) {
if (IP.includes('.')) {
return isIPv4(IP) ? 'IPv4' : 'Neither';
} else if (IP.includes(':')) {
return isIPv6(IP) ? 'IPv6' : 'Neither';
}
return 'Neither';
};