UNPKG

2.23 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.isIp = void 0;
4const 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}';
5const v6s = '[a-fA-F\\d]{1,4}';
6const v6 = `
7(?:
8(?:${v6s}:){7}(?:${v6s}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
9(?:${v6s}:){6}(?:${v4}|:${v6s}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
10(?:${v6s}:){5}(?::${v4}|(?::${v6s}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
11(?:${v6s}:){4}(?:(?::${v6s}){0,1}:${v4}|(?::${v6s}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
12(?:${v6s}:){3}(?:(?::${v6s}){0,2}:${v4}|(?::${v6s}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
13(?:${v6s}:){2}(?:(?::${v6s}){0,3}:${v4}|(?::${v6s}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
14(?:${v6s}:){1}(?:(?::${v6s}){0,4}:${v4}|(?::${v6s}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
15(?::(?:(?::${v6s}){0,5}:${v4}|(?::${v6s}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
16)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
17`.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim();
18const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
19const v4exact = new RegExp(`^${v4}$`);
20const v6exact = new RegExp(`^${v6}$`);
21/**
22 * @name isIp
23 * @summary Tests if the value is a valid IP address
24 * @description
25 * Checks to see if the value is a valid IP address. Optionally check for either v4/v6
26 * @example
27 * <BR>
28 *
29 * ```javascript
30 * import { isIp } from '@polkadot/util';
31 *
32 * isIp('192.168.0.1')); // => true
33 * isIp('1:2:3:4:5:6:7:8'); // => true
34 * isIp('192.168.0.1', 'v6')); // => false
35 * isIp('1:2:3:4:5:6:7:8', 'v4'); // => false
36 * ```
37 */
38function isIp(value, type) {
39 switch (type) {
40 case 'v4': return v4exact.test(value);
41 case 'v6': return v6exact.test(value);
42 default: return v46Exact.test(value);
43 }
44}
45exports.isIp = isIp;