/
isIp.js
62 lines (56 loc) · 1.68 KB
/
isIp.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
/* Check if value is an IP address.
*
* |Name |Desc |
* |------|------------------------------|
* |str |String to check |
* |return|True if value is an IP address|
*
* ### v4
*
* Check if value is an IPv4 address.
*
* ### v6
*
* Check if value is an IPv6 address.
*/
/* example
* isIp('192.168.191.1'); // -> true
* isIp('1:2:3:4:5:6:7:8'); // -> true
* isIp('test'); // -> false
* isIp.v4('192.168.191.1'); // -> true
* isIp.v6('1:2:3:4:5:6:7:8'); // -> true
*/
/* module
* env: all
* since: 1.5.1
*/
/* typescript
* export declare namespace isIp {
* function v4(str: string): boolean;
* function v6(str: string): boolean;
* }
* export declare function isIp(str: string): boolean;
*/
exports = str => {
return exports.v4(str) || exports.v6(str);
};
// https://github.com/sindresorhus/ip-regex
const v4 =
'(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';
const regV4 = new RegExp(`^${v4}$`);
const v6seg = '[a-fA-F\\d]{1,4}';
const v6 = [
'(',
`(?:${v6seg}:){7}(?:${v6seg}|:)|`,
`(?:${v6seg}:){6}(?:${v4}|:${v6seg}|:)|`,
`(?:${v6seg}:){5}(?::${v4}|(:${v6seg}){1,2}|:)|`,
`(?:${v6seg}:){4}(?:(:${v6seg}){0,1}:${v4}|(:${v6seg}){1,3}|:)|`,
`(?:${v6seg}:){3}(?:(:${v6seg}){0,2}:${v4}|(:${v6seg}){1,4}|:)|`,
`(?:${v6seg}:){2}(?:(:${v6seg}){0,3}:${v4}|(:${v6seg}){1,5}|:)|`,
`(?:${v6seg}:){1}(?:(:${v6seg}){0,4}:${v4}|(:${v6seg}){1,6}|:)|`,
`(?::((?::${v6seg}){0,5}:${v4}|(?::${v6seg}){1,7}|:))`,
')(%[0-9a-zA-Z]{1,})?'
].join('');
const regV6 = new RegExp(`^${v6}$`);
exports.v4 = str => regV4.test(str);
exports.v6 = str => regV6.test(str);