UNPKG

2.51 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = isIP;
7
8var _assertString = _interopRequireDefault(require("./util/assertString"));
9
10function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
12var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
13var ipv6Block = /^[0-9A-F]{1,4}$/i;
14
15function isIP(str) {
16 var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
17 (0, _assertString.default)(str);
18 version = String(version);
19
20 if (!version) {
21 return isIP(str, 4) || isIP(str, 6);
22 } else if (version === '4') {
23 if (!ipv4Maybe.test(str)) {
24 return false;
25 }
26
27 var parts = str.split('.').sort(function (a, b) {
28 return a - b;
29 });
30 return parts[3] <= 255;
31 } else if (version === '6') {
32 var blocks = str.split(':');
33 var foundOmissionBlock = false; // marker to indicate ::
34 // At least some OS accept the last 32 bits of an IPv6 address
35 // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
36 // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
37 // and '::a.b.c.d' is deprecated, but also valid.
38
39 var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);
40 var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;
41
42 if (blocks.length > expectedNumberOfBlocks) {
43 return false;
44 } // initial or final ::
45
46
47 if (str === '::') {
48 return true;
49 } else if (str.substr(0, 2) === '::') {
50 blocks.shift();
51 blocks.shift();
52 foundOmissionBlock = true;
53 } else if (str.substr(str.length - 2) === '::') {
54 blocks.pop();
55 blocks.pop();
56 foundOmissionBlock = true;
57 }
58
59 for (var i = 0; i < blocks.length; ++i) {
60 // test for a :: which can not be at the string start/end
61 // since those cases have been handled above
62 if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {
63 if (foundOmissionBlock) {
64 return false; // multiple :: in address
65 }
66
67 foundOmissionBlock = true;
68 } else if (foundIPv4TransitionBlock && i === blocks.length - 1) {// it has been checked before that the last
69 // block is a valid IPv4 address
70 } else if (!ipv6Block.test(blocks[i])) {
71 return false;
72 }
73 }
74
75 if (foundOmissionBlock) {
76 return blocks.length >= 1;
77 }
78
79 return blocks.length === expectedNumberOfBlocks;
80 }
81
82 return false;
83}
84
85module.exports = exports.default;
\No newline at end of file