-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvalidIPAddress.js
59 lines (46 loc) · 1.03 KB
/
validIPAddress.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
const isIPv4 = (IP) => {
const groups = IP.split('.')
if (groups.length !== 4) {
return false
}
const nums = groups.map(g => parseInt(g))
for (let i = 0; i < nums.length; i++) {
if (nums[i] < 0 || nums[i] > 255) {
return false
}
if (groups[i] !== nums[i].toString()) {
return false
}
}
return true
}
const isIPv6 = (IP) => {
const groups = IP.split(':')
if (groups.length !== 8) {
return false
}
const nums = groups.map(g => parseInt(g, 16))
for (let i = 0; i < nums.length; i++) {
if (nums[i] < 0 || nums[i] > 65535) {
return false
}
const paddedGroup = groups[i].padStart(4, '0').toUpperCase()
const paddedNum = nums[i].toString(16).padStart(4, '0').toUpperCase()
if (paddedGroup !== paddedNum) {
return false
}
}
return true
}
/**
* @param {string} IP
* @return {string}
*/
const validIPAddress = function (IP) {
return (
(isIPv4(IP) && 'IPv4') ||
(isIPv6(IP) && 'IPv6') ||
'Neither'
)
}
module.exports = validIPAddress