ipaddr.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. (function (root) {
  2. 'use strict';
  3. // A list of regular expressions that match arbitrary IPv4 addresses,
  4. // for which a number of weird notations exist.
  5. // Note that an address like 0010.0xa5.1.1 is considered legal.
  6. const ipv4Part = '(0?\\d+|0x[a-f0-9]+)';
  7. const ipv4Regexes = {
  8. fourOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, 'i'),
  9. threeOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, 'i'),
  10. twoOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}$`, 'i'),
  11. longValue: new RegExp(`^${ipv4Part}$`, 'i')
  12. };
  13. // Regular Expression for checking Octal numbers
  14. const octalRegex = new RegExp(`^0[0-7]+$`, 'i');
  15. const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');
  16. const zoneIndex = '%[0-9a-z]{1,}';
  17. // IPv6-matching regular expressions.
  18. // For IPv6, the task is simpler: it is enough to match the colon-delimited
  19. // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at
  20. // the end.
  21. const ipv6Part = '(?:[0-9a-f]+::?)+';
  22. const ipv6Regexes = {
  23. zoneIndex: new RegExp(zoneIndex, 'i'),
  24. 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),
  25. deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),
  26. transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?$`, 'i')
  27. };
  28. // Expand :: in an IPv6 address or address part consisting of `parts` groups.
  29. function expandIPv6 (string, parts) {
  30. // More than one '::' means invalid adddress
  31. if (string.indexOf('::') !== string.lastIndexOf('::')) {
  32. return null;
  33. }
  34. let colonCount = 0;
  35. let lastColon = -1;
  36. let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];
  37. let replacement, replacementCount;
  38. // Remove zone index and save it for later
  39. if (zoneId) {
  40. zoneId = zoneId.substring(1);
  41. string = string.replace(/%.+$/, '');
  42. }
  43. // How many parts do we already have?
  44. while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
  45. colonCount++;
  46. }
  47. // 0::0 is two parts more than ::
  48. if (string.substr(0, 2) === '::') {
  49. colonCount--;
  50. }
  51. if (string.substr(-2, 2) === '::') {
  52. colonCount--;
  53. }
  54. // The following loop would hang if colonCount > parts
  55. if (colonCount > parts) {
  56. return null;
  57. }
  58. // replacement = ':' + '0:' * (parts - colonCount)
  59. replacementCount = parts - colonCount;
  60. replacement = ':';
  61. while (replacementCount--) {
  62. replacement += '0:';
  63. }
  64. // Insert the missing zeroes
  65. string = string.replace('::', replacement);
  66. // Trim any garbage which may be hanging around if :: was at the edge in
  67. // the source strin
  68. if (string[0] === ':') {
  69. string = string.slice(1);
  70. }
  71. if (string[string.length - 1] === ':') {
  72. string = string.slice(0, -1);
  73. }
  74. parts = (function () {
  75. const ref = string.split(':');
  76. const results = [];
  77. for (let i = 0; i < ref.length; i++) {
  78. results.push(parseInt(ref[i], 16));
  79. }
  80. return results;
  81. })();
  82. return {
  83. parts: parts,
  84. zoneId: zoneId
  85. };
  86. }
  87. // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.
  88. function matchCIDR (first, second, partSize, cidrBits) {
  89. if (first.length !== second.length) {
  90. throw new Error('ipaddr: cannot match CIDR for objects with different lengths');
  91. }
  92. let part = 0;
  93. let shift;
  94. while (cidrBits > 0) {
  95. shift = partSize - cidrBits;
  96. if (shift < 0) {
  97. shift = 0;
  98. }
  99. if (first[part] >> shift !== second[part] >> shift) {
  100. return false;
  101. }
  102. cidrBits -= partSize;
  103. part += 1;
  104. }
  105. return true;
  106. }
  107. function parseIntAuto (string) {
  108. // Hexadedimal base 16 (0x#)
  109. if (hexRegex.test(string)) {
  110. return parseInt(string, 16);
  111. }
  112. // While octal representation is discouraged by ECMAScript 3
  113. // and forbidden by ECMAScript 5, we silently allow it to
  114. // work only if the rest of the string has numbers less than 8.
  115. if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {
  116. if (octalRegex.test(string)) {
  117. return parseInt(string, 8);
  118. }
  119. throw new Error(`ipaddr: cannot parse ${string} as octal`);
  120. }
  121. // Always include the base 10 radix!
  122. return parseInt(string, 10);
  123. }
  124. function padPart (part, length) {
  125. while (part.length < length) {
  126. part = `0${part}`;
  127. }
  128. return part;
  129. }
  130. const ipaddr = {};
  131. // An IPv4 address (RFC791).
  132. ipaddr.IPv4 = (function () {
  133. // Constructs a new IPv4 address from an array of four octets
  134. // in network order (MSB first)
  135. // Verifies the input.
  136. function IPv4 (octets) {
  137. if (octets.length !== 4) {
  138. throw new Error('ipaddr: ipv4 octet count should be 4');
  139. }
  140. let i, octet;
  141. for (i = 0; i < octets.length; i++) {
  142. octet = octets[i];
  143. if (!((0 <= octet && octet <= 255))) {
  144. throw new Error('ipaddr: ipv4 octet should fit in 8 bits');
  145. }
  146. }
  147. this.octets = octets;
  148. }
  149. // Special IPv4 address ranges.
  150. // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses
  151. IPv4.prototype.SpecialRanges = {
  152. unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
  153. broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
  154. // RFC3171
  155. multicast: [[new IPv4([224, 0, 0, 0]), 4]],
  156. // RFC3927
  157. linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
  158. // RFC5735
  159. loopback: [[new IPv4([127, 0, 0, 0]), 8]],
  160. // RFC6598
  161. carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
  162. // RFC1918
  163. 'private': [
  164. [new IPv4([10, 0, 0, 0]), 8],
  165. [new IPv4([172, 16, 0, 0]), 12],
  166. [new IPv4([192, 168, 0, 0]), 16]
  167. ],
  168. // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700
  169. reserved: [
  170. [new IPv4([192, 0, 0, 0]), 24],
  171. [new IPv4([192, 0, 2, 0]), 24],
  172. [new IPv4([192, 88, 99, 0]), 24],
  173. [new IPv4([198, 18, 0, 0]), 15],
  174. [new IPv4([198, 51, 100, 0]), 24],
  175. [new IPv4([203, 0, 113, 0]), 24],
  176. [new IPv4([240, 0, 0, 0]), 4]
  177. ],
  178. // RFC7534, RFC7535
  179. as112: [
  180. [new IPv4([192, 175, 48, 0]), 24],
  181. [new IPv4([192, 31, 196, 0]), 24],
  182. ],
  183. // RFC7450
  184. amt: [
  185. [new IPv4([192, 52, 193, 0]), 24],
  186. ],
  187. };
  188. // The 'kind' method exists on both IPv4 and IPv6 classes.
  189. IPv4.prototype.kind = function () {
  190. return 'ipv4';
  191. };
  192. // Checks if this address matches other one within given CIDR range.
  193. IPv4.prototype.match = function (other, cidrRange) {
  194. let ref;
  195. if (cidrRange === undefined) {
  196. ref = other;
  197. other = ref[0];
  198. cidrRange = ref[1];
  199. }
  200. if (other.kind() !== 'ipv4') {
  201. throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');
  202. }
  203. return matchCIDR(this.octets, other.octets, 8, cidrRange);
  204. };
  205. // returns a number of leading ones in IPv4 address, making sure that
  206. // the rest is a solid sequence of 0's (valid netmask)
  207. // returns either the CIDR length or null if mask is not valid
  208. IPv4.prototype.prefixLengthFromSubnetMask = function () {
  209. let cidr = 0;
  210. // non-zero encountered stop scanning for zeroes
  211. let stop = false;
  212. // number of zeroes in octet
  213. const zerotable = {
  214. 0: 8,
  215. 128: 7,
  216. 192: 6,
  217. 224: 5,
  218. 240: 4,
  219. 248: 3,
  220. 252: 2,
  221. 254: 1,
  222. 255: 0
  223. };
  224. let i, octet, zeros;
  225. for (i = 3; i >= 0; i -= 1) {
  226. octet = this.octets[i];
  227. if (octet in zerotable) {
  228. zeros = zerotable[octet];
  229. if (stop && zeros !== 0) {
  230. return null;
  231. }
  232. if (zeros !== 8) {
  233. stop = true;
  234. }
  235. cidr += zeros;
  236. } else {
  237. return null;
  238. }
  239. }
  240. return 32 - cidr;
  241. };
  242. // Checks if the address corresponds to one of the special ranges.
  243. IPv4.prototype.range = function () {
  244. return ipaddr.subnetMatch(this, this.SpecialRanges);
  245. };
  246. // Returns an array of byte-sized values in network order (MSB first)
  247. IPv4.prototype.toByteArray = function () {
  248. return this.octets.slice(0);
  249. };
  250. // Converts this IPv4 address to an IPv4-mapped IPv6 address.
  251. IPv4.prototype.toIPv4MappedAddress = function () {
  252. return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);
  253. };
  254. // Symmetrical method strictly for aligning with the IPv6 methods.
  255. IPv4.prototype.toNormalizedString = function () {
  256. return this.toString();
  257. };
  258. // Returns the address in convenient, decimal-dotted format.
  259. IPv4.prototype.toString = function () {
  260. return this.octets.join('.');
  261. };
  262. return IPv4;
  263. })();
  264. // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation
  265. ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {
  266. try {
  267. const cidr = this.parseCIDR(string);
  268. const ipInterfaceOctets = cidr[0].toByteArray();
  269. const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  270. const octets = [];
  271. let i = 0;
  272. while (i < 4) {
  273. // Broadcast address is bitwise OR between ip interface and inverted mask
  274. octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
  275. i++;
  276. }
  277. return new this(octets);
  278. } catch (e) {
  279. throw new Error('ipaddr: the address does not have IPv4 CIDR format');
  280. }
  281. };
  282. // Checks if a given string is formatted like IPv4 address.
  283. ipaddr.IPv4.isIPv4 = function (string) {
  284. return this.parser(string) !== null;
  285. };
  286. // Checks if a given string is a valid IPv4 address.
  287. ipaddr.IPv4.isValid = function (string) {
  288. try {
  289. new this(this.parser(string));
  290. return true;
  291. } catch (e) {
  292. return false;
  293. }
  294. };
  295. // Checks if a given string is a valid IPv4 address in CIDR notation.
  296. ipaddr.IPv4.isValidCIDR = function (string) {
  297. try {
  298. this.parseCIDR(string);
  299. return true;
  300. } catch (e) {
  301. return false;
  302. }
  303. };
  304. // Checks if a given string is a full four-part IPv4 Address.
  305. ipaddr.IPv4.isValidFourPartDecimal = function (string) {
  306. if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
  307. return true;
  308. } else {
  309. return false;
  310. }
  311. };
  312. // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation
  313. ipaddr.IPv4.networkAddressFromCIDR = function (string) {
  314. let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
  315. try {
  316. cidr = this.parseCIDR(string);
  317. ipInterfaceOctets = cidr[0].toByteArray();
  318. subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  319. octets = [];
  320. i = 0;
  321. while (i < 4) {
  322. // Network address is bitwise AND between ip interface and mask
  323. octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
  324. i++;
  325. }
  326. return new this(octets);
  327. } catch (e) {
  328. throw new Error('ipaddr: the address does not have IPv4 CIDR format');
  329. }
  330. };
  331. // Tries to parse and validate a string with IPv4 address.
  332. // Throws an error if it fails.
  333. ipaddr.IPv4.parse = function (string) {
  334. const parts = this.parser(string);
  335. if (parts === null) {
  336. throw new Error('ipaddr: string is not formatted like an IPv4 Address');
  337. }
  338. return new this(parts);
  339. };
  340. // Parses the string as an IPv4 Address with CIDR Notation.
  341. ipaddr.IPv4.parseCIDR = function (string) {
  342. let match;
  343. if ((match = string.match(/^(.+)\/(\d+)$/))) {
  344. const maskLength = parseInt(match[2]);
  345. if (maskLength >= 0 && maskLength <= 32) {
  346. const parsed = [this.parse(match[1]), maskLength];
  347. Object.defineProperty(parsed, 'toString', {
  348. value: function () {
  349. return this.join('/');
  350. }
  351. });
  352. return parsed;
  353. }
  354. }
  355. throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');
  356. };
  357. // Classful variants (like a.b, where a is an octet, and b is a 24-bit
  358. // value representing last three octets; this corresponds to a class C
  359. // address) are omitted due to classless nature of modern Internet.
  360. ipaddr.IPv4.parser = function (string) {
  361. let match, part, value;
  362. // parseInt recognizes all that octal & hexadecimal weirdness for us
  363. if ((match = string.match(ipv4Regexes.fourOctet))) {
  364. return (function () {
  365. const ref = match.slice(1, 6);
  366. const results = [];
  367. for (let i = 0; i < ref.length; i++) {
  368. part = ref[i];
  369. results.push(parseIntAuto(part));
  370. }
  371. return results;
  372. })();
  373. } else if ((match = string.match(ipv4Regexes.longValue))) {
  374. value = parseIntAuto(match[1]);
  375. if (value > 0xffffffff || value < 0) {
  376. throw new Error('ipaddr: address outside defined range');
  377. }
  378. return ((function () {
  379. const results = [];
  380. let shift;
  381. for (shift = 0; shift <= 24; shift += 8) {
  382. results.push((value >> shift) & 0xff);
  383. }
  384. return results;
  385. })()).reverse();
  386. } else if ((match = string.match(ipv4Regexes.twoOctet))) {
  387. return (function () {
  388. const ref = match.slice(1, 4);
  389. const results = [];
  390. value = parseIntAuto(ref[1]);
  391. if (value > 0xffffff || value < 0) {
  392. throw new Error('ipaddr: address outside defined range');
  393. }
  394. results.push(parseIntAuto(ref[0]));
  395. results.push((value >> 16) & 0xff);
  396. results.push((value >> 8) & 0xff);
  397. results.push( value & 0xff);
  398. return results;
  399. })();
  400. } else if ((match = string.match(ipv4Regexes.threeOctet))) {
  401. return (function () {
  402. const ref = match.slice(1, 5);
  403. const results = [];
  404. value = parseIntAuto(ref[2]);
  405. if (value > 0xffff || value < 0) {
  406. throw new Error('ipaddr: address outside defined range');
  407. }
  408. results.push(parseIntAuto(ref[0]));
  409. results.push(parseIntAuto(ref[1]));
  410. results.push((value >> 8) & 0xff);
  411. results.push( value & 0xff);
  412. return results;
  413. })();
  414. } else {
  415. return null;
  416. }
  417. };
  418. // A utility function to return subnet mask in IPv4 format given the prefix length
  419. ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {
  420. prefix = parseInt(prefix);
  421. if (prefix < 0 || prefix > 32) {
  422. throw new Error('ipaddr: invalid IPv4 prefix length');
  423. }
  424. const octets = [0, 0, 0, 0];
  425. let j = 0;
  426. const filledOctetCount = Math.floor(prefix / 8);
  427. while (j < filledOctetCount) {
  428. octets[j] = 255;
  429. j++;
  430. }
  431. if (filledOctetCount < 4) {
  432. octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
  433. }
  434. return new this(octets);
  435. };
  436. // An IPv6 address (RFC2460)
  437. ipaddr.IPv6 = (function () {
  438. // Constructs an IPv6 address from an array of eight 16 - bit parts
  439. // or sixteen 8 - bit parts in network order(MSB first).
  440. // Throws an error if the input is invalid.
  441. function IPv6 (parts, zoneId) {
  442. let i, part;
  443. if (parts.length === 16) {
  444. this.parts = [];
  445. for (i = 0; i <= 14; i += 2) {
  446. this.parts.push((parts[i] << 8) | parts[i + 1]);
  447. }
  448. } else if (parts.length === 8) {
  449. this.parts = parts;
  450. } else {
  451. throw new Error('ipaddr: ipv6 part count should be 8 or 16');
  452. }
  453. for (i = 0; i < this.parts.length; i++) {
  454. part = this.parts[i];
  455. if (!((0 <= part && part <= 0xffff))) {
  456. throw new Error('ipaddr: ipv6 part should fit in 16 bits');
  457. }
  458. }
  459. if (zoneId) {
  460. this.zoneId = zoneId;
  461. }
  462. }
  463. // Special IPv6 ranges
  464. IPv6.prototype.SpecialRanges = {
  465. // RFC4291, here and after
  466. unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
  467. linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
  468. multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
  469. loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
  470. uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
  471. ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
  472. // RFC6666
  473. discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64],
  474. // RFC6145
  475. rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
  476. // RFC6052
  477. rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
  478. // RFC3056
  479. '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
  480. // RFC6052, RFC6146
  481. teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
  482. // RFC5180
  483. benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48],
  484. // RFC7450
  485. amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32],
  486. as112v6: [
  487. [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48],
  488. [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48],
  489. ],
  490. deprecated: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28],
  491. orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28],
  492. droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28],
  493. reserved: [
  494. // RFC3849
  495. [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23],
  496. // RFC2928
  497. [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32],
  498. ],
  499. };
  500. // Checks if this address is an IPv4-mapped IPv6 address.
  501. IPv6.prototype.isIPv4MappedAddress = function () {
  502. return this.range() === 'ipv4Mapped';
  503. };
  504. // The 'kind' method exists on both IPv4 and IPv6 classes.
  505. IPv6.prototype.kind = function () {
  506. return 'ipv6';
  507. };
  508. // Checks if this address matches other one within given CIDR range.
  509. IPv6.prototype.match = function (other, cidrRange) {
  510. let ref;
  511. if (cidrRange === undefined) {
  512. ref = other;
  513. other = ref[0];
  514. cidrRange = ref[1];
  515. }
  516. if (other.kind() !== 'ipv6') {
  517. throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');
  518. }
  519. return matchCIDR(this.parts, other.parts, 16, cidrRange);
  520. };
  521. // returns a number of leading ones in IPv6 address, making sure that
  522. // the rest is a solid sequence of 0's (valid netmask)
  523. // returns either the CIDR length or null if mask is not valid
  524. IPv6.prototype.prefixLengthFromSubnetMask = function () {
  525. let cidr = 0;
  526. // non-zero encountered stop scanning for zeroes
  527. let stop = false;
  528. // number of zeroes in octet
  529. const zerotable = {
  530. 0: 16,
  531. 32768: 15,
  532. 49152: 14,
  533. 57344: 13,
  534. 61440: 12,
  535. 63488: 11,
  536. 64512: 10,
  537. 65024: 9,
  538. 65280: 8,
  539. 65408: 7,
  540. 65472: 6,
  541. 65504: 5,
  542. 65520: 4,
  543. 65528: 3,
  544. 65532: 2,
  545. 65534: 1,
  546. 65535: 0
  547. };
  548. let part, zeros;
  549. for (let i = 7; i >= 0; i -= 1) {
  550. part = this.parts[i];
  551. if (part in zerotable) {
  552. zeros = zerotable[part];
  553. if (stop && zeros !== 0) {
  554. return null;
  555. }
  556. if (zeros !== 16) {
  557. stop = true;
  558. }
  559. cidr += zeros;
  560. } else {
  561. return null;
  562. }
  563. }
  564. return 128 - cidr;
  565. };
  566. // Checks if the address corresponds to one of the special ranges.
  567. IPv6.prototype.range = function () {
  568. return ipaddr.subnetMatch(this, this.SpecialRanges);
  569. };
  570. // Returns an array of byte-sized values in network order (MSB first)
  571. IPv6.prototype.toByteArray = function () {
  572. let part;
  573. const bytes = [];
  574. const ref = this.parts;
  575. for (let i = 0; i < ref.length; i++) {
  576. part = ref[i];
  577. bytes.push(part >> 8);
  578. bytes.push(part & 0xff);
  579. }
  580. return bytes;
  581. };
  582. // Returns the address in expanded format with all zeroes included, like
  583. // 2001:0db8:0008:0066:0000:0000:0000:0001
  584. IPv6.prototype.toFixedLengthString = function () {
  585. const addr = ((function () {
  586. const results = [];
  587. for (let i = 0; i < this.parts.length; i++) {
  588. results.push(padPart(this.parts[i].toString(16), 4));
  589. }
  590. return results;
  591. }).call(this)).join(':');
  592. let suffix = '';
  593. if (this.zoneId) {
  594. suffix = `%${this.zoneId}`;
  595. }
  596. return addr + suffix;
  597. };
  598. // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.
  599. // Throws an error otherwise.
  600. IPv6.prototype.toIPv4Address = function () {
  601. if (!this.isIPv4MappedAddress()) {
  602. throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');
  603. }
  604. const ref = this.parts.slice(-2);
  605. const high = ref[0];
  606. const low = ref[1];
  607. return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
  608. };
  609. // Returns the address in expanded format with all zeroes included, like
  610. // 2001:db8:8:66:0:0:0:1
  611. //
  612. // Deprecated: use toFixedLengthString() instead.
  613. IPv6.prototype.toNormalizedString = function () {
  614. const addr = ((function () {
  615. const results = [];
  616. for (let i = 0; i < this.parts.length; i++) {
  617. results.push(this.parts[i].toString(16));
  618. }
  619. return results;
  620. }).call(this)).join(':');
  621. let suffix = '';
  622. if (this.zoneId) {
  623. suffix = `%${this.zoneId}`;
  624. }
  625. return addr + suffix;
  626. };
  627. // Returns the address in compact, human-readable format like
  628. // 2001:db8:8:66::1
  629. // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)
  630. IPv6.prototype.toRFC5952String = function () {
  631. const regex = /((^|:)(0(:|$)){2,})/g;
  632. const string = this.toNormalizedString();
  633. let bestMatchIndex = 0;
  634. let bestMatchLength = -1;
  635. let match;
  636. while ((match = regex.exec(string))) {
  637. if (match[0].length > bestMatchLength) {
  638. bestMatchIndex = match.index;
  639. bestMatchLength = match[0].length;
  640. }
  641. }
  642. if (bestMatchLength < 0) {
  643. return string;
  644. }
  645. return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;
  646. };
  647. // Returns the address in compact, human-readable format like
  648. // 2001:db8:8:66::1
  649. // Calls toRFC5952String under the hood.
  650. IPv6.prototype.toString = function () {
  651. return this.toRFC5952String();
  652. };
  653. return IPv6;
  654. })();
  655. // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation
  656. ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {
  657. try {
  658. const cidr = this.parseCIDR(string);
  659. const ipInterfaceOctets = cidr[0].toByteArray();
  660. const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  661. const octets = [];
  662. let i = 0;
  663. while (i < 16) {
  664. // Broadcast address is bitwise OR between ip interface and inverted mask
  665. octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
  666. i++;
  667. }
  668. return new this(octets);
  669. } catch (e) {
  670. throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);
  671. }
  672. };
  673. // Checks if a given string is formatted like IPv6 address.
  674. ipaddr.IPv6.isIPv6 = function (string) {
  675. return this.parser(string) !== null;
  676. };
  677. // Checks to see if string is a valid IPv6 Address
  678. ipaddr.IPv6.isValid = function (string) {
  679. // Since IPv6.isValid is always called first, this shortcut
  680. // provides a substantial performance gain.
  681. if (typeof string === 'string' && string.indexOf(':') === -1) {
  682. return false;
  683. }
  684. try {
  685. const addr = this.parser(string);
  686. new this(addr.parts, addr.zoneId);
  687. return true;
  688. } catch (e) {
  689. return false;
  690. }
  691. };
  692. // Checks if a given string is a valid IPv6 address in CIDR notation.
  693. ipaddr.IPv6.isValidCIDR = function (string) {
  694. // See note in IPv6.isValid
  695. if (typeof string === 'string' && string.indexOf(':') === -1) {
  696. return false;
  697. }
  698. try {
  699. this.parseCIDR(string);
  700. return true;
  701. } catch (e) {
  702. return false;
  703. }
  704. };
  705. // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation
  706. ipaddr.IPv6.networkAddressFromCIDR = function (string) {
  707. let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
  708. try {
  709. cidr = this.parseCIDR(string);
  710. ipInterfaceOctets = cidr[0].toByteArray();
  711. subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  712. octets = [];
  713. i = 0;
  714. while (i < 16) {
  715. // Network address is bitwise AND between ip interface and mask
  716. octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
  717. i++;
  718. }
  719. return new this(octets);
  720. } catch (e) {
  721. throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);
  722. }
  723. };
  724. // Tries to parse and validate a string with IPv6 address.
  725. // Throws an error if it fails.
  726. ipaddr.IPv6.parse = function (string) {
  727. const addr = this.parser(string);
  728. if (addr.parts === null) {
  729. throw new Error('ipaddr: string is not formatted like an IPv6 Address');
  730. }
  731. return new this(addr.parts, addr.zoneId);
  732. };
  733. ipaddr.IPv6.parseCIDR = function (string) {
  734. let maskLength, match, parsed;
  735. if ((match = string.match(/^(.+)\/(\d+)$/))) {
  736. maskLength = parseInt(match[2]);
  737. if (maskLength >= 0 && maskLength <= 128) {
  738. parsed = [this.parse(match[1]), maskLength];
  739. Object.defineProperty(parsed, 'toString', {
  740. value: function () {
  741. return this.join('/');
  742. }
  743. });
  744. return parsed;
  745. }
  746. }
  747. throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');
  748. };
  749. // Parse an IPv6 address.
  750. ipaddr.IPv6.parser = function (string) {
  751. let addr, i, match, octet, octets, zoneId;
  752. if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {
  753. return this.parser(`::ffff:${match[1]}`);
  754. }
  755. if (ipv6Regexes.native.test(string)) {
  756. return expandIPv6(string, 8);
  757. }
  758. if ((match = string.match(ipv6Regexes.transitional))) {
  759. zoneId = match[6] || '';
  760. addr = match[1]
  761. if (!match[1].endsWith('::')) {
  762. addr = addr.slice(0, -1)
  763. }
  764. addr = expandIPv6(addr + zoneId, 6);
  765. if (addr.parts) {
  766. octets = [
  767. parseInt(match[2]),
  768. parseInt(match[3]),
  769. parseInt(match[4]),
  770. parseInt(match[5])
  771. ];
  772. for (i = 0; i < octets.length; i++) {
  773. octet = octets[i];
  774. if (!((0 <= octet && octet <= 255))) {
  775. return null;
  776. }
  777. }
  778. addr.parts.push(octets[0] << 8 | octets[1]);
  779. addr.parts.push(octets[2] << 8 | octets[3]);
  780. return {
  781. parts: addr.parts,
  782. zoneId: addr.zoneId
  783. };
  784. }
  785. }
  786. return null;
  787. };
  788. // A utility function to return subnet mask in IPv6 format given the prefix length
  789. ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {
  790. prefix = parseInt(prefix);
  791. if (prefix < 0 || prefix > 128) {
  792. throw new Error('ipaddr: invalid IPv6 prefix length');
  793. }
  794. const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  795. let j = 0;
  796. const filledOctetCount = Math.floor(prefix / 8);
  797. while (j < filledOctetCount) {
  798. octets[j] = 255;
  799. j++;
  800. }
  801. if (filledOctetCount < 16) {
  802. octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
  803. }
  804. return new this(octets);
  805. };
  806. // Try to parse an array in network order (MSB first) for IPv4 and IPv6
  807. ipaddr.fromByteArray = function (bytes) {
  808. const length = bytes.length;
  809. if (length === 4) {
  810. return new ipaddr.IPv4(bytes);
  811. } else if (length === 16) {
  812. return new ipaddr.IPv6(bytes);
  813. } else {
  814. throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');
  815. }
  816. };
  817. // Checks if the address is valid IP address
  818. ipaddr.isValid = function (string) {
  819. return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
  820. };
  821. // Checks if the address is valid IP address in CIDR notation
  822. ipaddr.isValidCIDR = function (string) {
  823. return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);
  824. };
  825. // Attempts to parse an IP Address, first through IPv6 then IPv4.
  826. // Throws an error if it could not be parsed.
  827. ipaddr.parse = function (string) {
  828. if (ipaddr.IPv6.isValid(string)) {
  829. return ipaddr.IPv6.parse(string);
  830. } else if (ipaddr.IPv4.isValid(string)) {
  831. return ipaddr.IPv4.parse(string);
  832. } else {
  833. throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');
  834. }
  835. };
  836. // Attempt to parse CIDR notation, first through IPv6 then IPv4.
  837. // Throws an error if it could not be parsed.
  838. ipaddr.parseCIDR = function (string) {
  839. try {
  840. return ipaddr.IPv6.parseCIDR(string);
  841. } catch (e) {
  842. try {
  843. return ipaddr.IPv4.parseCIDR(string);
  844. } catch (e2) {
  845. throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');
  846. }
  847. }
  848. };
  849. // Parse an address and return plain IPv4 address if it is an IPv4-mapped address
  850. ipaddr.process = function (string) {
  851. const addr = this.parse(string);
  852. if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
  853. return addr.toIPv4Address();
  854. } else {
  855. return addr;
  856. }
  857. };
  858. // An utility function to ease named range matching. See examples below.
  859. // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors
  860. // on matching IPv4 addresses to IPv6 ranges or vice versa.
  861. ipaddr.subnetMatch = function (address, rangeList, defaultName) {
  862. let i, rangeName, rangeSubnets, subnet;
  863. if (defaultName === undefined || defaultName === null) {
  864. defaultName = 'unicast';
  865. }
  866. for (rangeName in rangeList) {
  867. if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {
  868. rangeSubnets = rangeList[rangeName];
  869. // ECMA5 Array.isArray isn't available everywhere
  870. if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
  871. rangeSubnets = [rangeSubnets];
  872. }
  873. for (i = 0; i < rangeSubnets.length; i++) {
  874. subnet = rangeSubnets[i];
  875. if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {
  876. return rangeName;
  877. }
  878. }
  879. }
  880. }
  881. return defaultName;
  882. };
  883. // Export for both the CommonJS and browser-like environment
  884. if (typeof module !== 'undefined' && module.exports) {
  885. module.exports = ipaddr;
  886. } else {
  887. root.ipaddr = ipaddr;
  888. }
  889. }(this));