Skip to content

Commit 9cbc46f

Browse files
authored
Update 468-validate-ip-address.js
1 parent 8f32970 commit 9cbc46f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

468-validate-ip-address.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,37 @@
1+
/**
2+
* @param {string} IP
3+
* @return {string}
4+
*/
5+
const validIPAddress = function (IP) {
6+
if (IP.indexOf('.') > 0) return validIPv4(IP) ? 'IPv4' : 'Neither'
7+
else return validIPv6(IP) ? 'IPv6' : 'Neither'
8+
}
9+
10+
const validIPv4 = function (IP) {
11+
const strs = IP.split('.')
12+
if (strs.length !== 4) return false
13+
for (let str of strs) {
14+
if (str.length === 0) return false
15+
if (str.match(/[^0-9]/)) return false
16+
if (str.length > 1 && str.charAt(0) === '0') return false
17+
if (+str > 255) return false
18+
}
19+
return true
20+
}
21+
22+
const validIPv6 = function (IP) {
23+
const strs = IP.split(':')
24+
if (strs.length !== 8) return false
25+
for (let str of strs) {
26+
if (str.length === 0) return false
27+
if (str.length > 4) return false
28+
if (str.match(/[^0-9a-fA-F]/g)) return false
29+
}
30+
return true
31+
}
32+
33+
// another
34+
135
/**
236
* @param {string} IP
337
* @return {string}

0 commit comments

Comments
 (0)