ipaddr.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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 address
  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 string
  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. // Hexadecimal 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. // Checks if a given string is a full four-part IPv4 Address with CIDR prefix.
  313. ipaddr.IPv4.isValidCIDRFourPartDecimal = function (string) {
  314. const match = string.match(/^(.+)\/(\d+)$/);
  315. if (!ipaddr.IPv4.isValidCIDR(string) || !match) {
  316. return false;
  317. }
  318. return ipaddr.IPv4.isValidFourPartDecimal(match[1]);
  319. };
  320. // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation
  321. ipaddr.IPv4.networkAddressFromCIDR = function (string) {
  322. let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
  323. try {
  324. cidr = this.parseCIDR(string);
  325. ipInterfaceOctets = cidr[0].toByteArray();
  326. subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  327. octets = [];
  328. i = 0;
  329. while (i < 4) {
  330. // Network address is bitwise AND between ip interface and mask
  331. octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
  332. i++;
  333. }
  334. return new this(octets);
  335. } catch (e) {
  336. throw new Error('ipaddr: the address does not have IPv4 CIDR format');
  337. }
  338. };
  339. // Tries to parse and validate a string with IPv4 address.
  340. // Throws an error if it fails.
  341. ipaddr.IPv4.parse = function (string) {
  342. const parts = this.parser(string);
  343. if (parts === null) {
  344. throw new Error('ipaddr: string is not formatted like an IPv4 Address');
  345. }
  346. return new this(parts);
  347. };
  348. // Parses the string as an IPv4 Address with CIDR Notation.
  349. ipaddr.IPv4.parseCIDR = function (string) {
  350. let match;
  351. if ((match = string.match(/^(.+)\/(\d+)$/))) {
  352. const maskLength = parseInt(match[2]);
  353. if (maskLength >= 0 && maskLength <= 32) {
  354. const parsed = [this.parse(match[1]), maskLength];
  355. Object.defineProperty(parsed, 'toString', {
  356. value: function () {
  357. return this.join('/');
  358. }
  359. });
  360. return parsed;
  361. }
  362. }
  363. throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');
  364. };
  365. // Classful variants (like a.b, where a is an octet, and b is a 24-bit
  366. // value representing last three octets; this corresponds to a class C
  367. // address) are omitted due to classless nature of modern Internet.
  368. ipaddr.IPv4.parser = function (string) {
  369. let match, part, value;
  370. // parseInt recognizes all that octal & hexadecimal weirdness for us
  371. if ((match = string.match(ipv4Regexes.fourOctet))) {
  372. return (function () {
  373. const ref = match.slice(1, 6);
  374. const results = [];
  375. for (let i = 0; i < ref.length; i++) {
  376. part = ref[i];
  377. results.push(parseIntAuto(part));
  378. }
  379. return results;
  380. })();
  381. } else if ((match = string.match(ipv4Regexes.longValue))) {
  382. value = parseIntAuto(match[1]);
  383. if (value > 0xffffffff || value < 0) {
  384. throw new Error('ipaddr: address outside defined range');
  385. }
  386. return ((function () {
  387. const results = [];
  388. let shift;
  389. for (shift = 0; shift <= 24; shift += 8) {
  390. results.push((value >> shift) & 0xff);
  391. }
  392. return results;
  393. })()).reverse();
  394. } else if ((match = string.match(ipv4Regexes.twoOctet))) {
  395. return (function () {
  396. const ref = match.slice(1, 4);
  397. const results = [];
  398. value = parseIntAuto(ref[1]);
  399. if (value > 0xffffff || value < 0) {
  400. throw new Error('ipaddr: address outside defined range');
  401. }
  402. results.push(parseIntAuto(ref[0]));
  403. results.push((value >> 16) & 0xff);
  404. results.push((value >> 8) & 0xff);
  405. results.push( value & 0xff);
  406. return results;
  407. })();
  408. } else if ((match = string.match(ipv4Regexes.threeOctet))) {
  409. return (function () {
  410. const ref = match.slice(1, 5);
  411. const results = [];
  412. value = parseIntAuto(ref[2]);
  413. if (value > 0xffff || value < 0) {
  414. throw new Error('ipaddr: address outside defined range');
  415. }
  416. results.push(parseIntAuto(ref[0]));
  417. results.push(parseIntAuto(ref[1]));
  418. results.push((value >> 8) & 0xff);
  419. results.push( value & 0xff);
  420. return results;
  421. })();
  422. } else {
  423. return null;
  424. }
  425. };
  426. // A utility function to return subnet mask in IPv4 format given the prefix length
  427. ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {
  428. prefix = parseInt(prefix);
  429. if (prefix < 0 || prefix > 32) {
  430. throw new Error('ipaddr: invalid IPv4 prefix length');
  431. }
  432. const octets = [0, 0, 0, 0];
  433. let j = 0;
  434. const filledOctetCount = Math.floor(prefix / 8);
  435. while (j < filledOctetCount) {
  436. octets[j] = 255;
  437. j++;
  438. }
  439. if (filledOctetCount < 4) {
  440. octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
  441. }
  442. return new this(octets);
  443. };
  444. // An IPv6 address (RFC2460)
  445. ipaddr.IPv6 = (function () {
  446. // Constructs an IPv6 address from an array of eight 16 - bit parts
  447. // or sixteen 8 - bit parts in network order(MSB first).
  448. // Throws an error if the input is invalid.
  449. function IPv6 (parts, zoneId) {
  450. let i, part;
  451. if (parts.length === 16) {
  452. this.parts = [];
  453. for (i = 0; i <= 14; i += 2) {
  454. this.parts.push((parts[i] << 8) | parts[i + 1]);
  455. }
  456. } else if (parts.length === 8) {
  457. this.parts = parts;
  458. } else {
  459. throw new Error('ipaddr: ipv6 part count should be 8 or 16');
  460. }
  461. for (i = 0; i < this.parts.length; i++) {
  462. part = this.parts[i];
  463. if (!((0 <= part && part <= 0xffff))) {
  464. throw new Error('ipaddr: ipv6 part should fit in 16 bits');
  465. }
  466. }
  467. if (zoneId) {
  468. this.zoneId = zoneId;
  469. }
  470. }
  471. // Special IPv6 ranges
  472. IPv6.prototype.SpecialRanges = {
  473. // RFC4291, here and after
  474. unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
  475. linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
  476. multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
  477. loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
  478. uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
  479. ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
  480. // RFC3879
  481. deprecatedSiteLocal: [new IPv6([0xfec0, 0, 0, 0, 0, 0, 0, 0]), 10],
  482. // RFC6666
  483. discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64],
  484. // RFC6145
  485. rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
  486. rfc6052: [
  487. // RFC6052
  488. [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
  489. // RFC8215
  490. [new IPv6([0x64, 0xff9b, 0x1, 0, 0, 0, 0, 0]), 48],
  491. ],
  492. // RFC3056
  493. '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
  494. // RFC6052, RFC6146
  495. teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
  496. // RFC5180
  497. benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48],
  498. // RFC7450
  499. amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32],
  500. as112v6: [
  501. // RFC7535
  502. [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48],
  503. // RFC7534
  504. [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48],
  505. ],
  506. // RFC4843
  507. deprecatedOrchid: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28],
  508. // RFC7343
  509. orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28],
  510. // RFC9374
  511. droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28],
  512. // RFC9602
  513. segmentRouting: [new IPv6([0x5f00, 0, 0, 0, 0, 0, 0, 0]), 16],
  514. reserved: [
  515. // RFC3849
  516. [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23],
  517. // RFC2928
  518. [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32],
  519. // RFC9637
  520. [new IPv6([0x3fff, 0, 0, 0, 0, 0, 0, 0]), 20],
  521. ],
  522. };
  523. // Checks if this address is an IPv4-mapped IPv6 address.
  524. IPv6.prototype.isIPv4MappedAddress = function () {
  525. return this.range() === 'ipv4Mapped';
  526. };
  527. // The 'kind' method exists on both IPv4 and IPv6 classes.
  528. IPv6.prototype.kind = function () {
  529. return 'ipv6';
  530. };
  531. // Checks if this address matches other one within given CIDR range.
  532. IPv6.prototype.match = function (other, cidrRange) {
  533. let ref;
  534. if (cidrRange === undefined) {
  535. ref = other;
  536. other = ref[0];
  537. cidrRange = ref[1];
  538. }
  539. if (other.kind() !== 'ipv6') {
  540. throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');
  541. }
  542. return matchCIDR(this.parts, other.parts, 16, cidrRange);
  543. };
  544. // returns a number of leading ones in IPv6 address, making sure that
  545. // the rest is a solid sequence of 0's (valid netmask)
  546. // returns either the CIDR length or null if mask is not valid
  547. IPv6.prototype.prefixLengthFromSubnetMask = function () {
  548. let cidr = 0;
  549. // non-zero encountered stop scanning for zeroes
  550. let stop = false;
  551. // number of zeroes in octet
  552. const zerotable = {
  553. 0: 16,
  554. 32768: 15,
  555. 49152: 14,
  556. 57344: 13,
  557. 61440: 12,
  558. 63488: 11,
  559. 64512: 10,
  560. 65024: 9,
  561. 65280: 8,
  562. 65408: 7,
  563. 65472: 6,
  564. 65504: 5,
  565. 65520: 4,
  566. 65528: 3,
  567. 65532: 2,
  568. 65534: 1,
  569. 65535: 0
  570. };
  571. let part, zeros;
  572. for (let i = 7; i >= 0; i -= 1) {
  573. part = this.parts[i];
  574. if (part in zerotable) {
  575. zeros = zerotable[part];
  576. if (stop && zeros !== 0) {
  577. return null;
  578. }
  579. if (zeros !== 16) {
  580. stop = true;
  581. }
  582. cidr += zeros;
  583. } else {
  584. return null;
  585. }
  586. }
  587. return 128 - cidr;
  588. };
  589. // Checks if the address corresponds to one of the special ranges.
  590. IPv6.prototype.range = function () {
  591. return ipaddr.subnetMatch(this, this.SpecialRanges);
  592. };
  593. // Returns an array of byte-sized values in network order (MSB first)
  594. IPv6.prototype.toByteArray = function () {
  595. let part;
  596. const bytes = [];
  597. const ref = this.parts;
  598. for (let i = 0; i < ref.length; i++) {
  599. part = ref[i];
  600. bytes.push(part >> 8);
  601. bytes.push(part & 0xff);
  602. }
  603. return bytes;
  604. };
  605. // Returns the address in expanded format with all zeroes included, like
  606. // 2001:0db8:0008:0066:0000:0000:0000:0001
  607. IPv6.prototype.toFixedLengthString = function () {
  608. const addr = ((function () {
  609. const results = [];
  610. for (let i = 0; i < this.parts.length; i++) {
  611. results.push(padPart(this.parts[i].toString(16), 4));
  612. }
  613. return results;
  614. }).call(this)).join(':');
  615. let suffix = '';
  616. if (this.zoneId) {
  617. suffix = `%${this.zoneId}`;
  618. }
  619. return addr + suffix;
  620. };
  621. // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.
  622. // Throws an error otherwise.
  623. IPv6.prototype.toIPv4Address = function () {
  624. if (!this.isIPv4MappedAddress()) {
  625. throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');
  626. }
  627. const ref = this.parts.slice(-2);
  628. const high = ref[0];
  629. const low = ref[1];
  630. return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
  631. };
  632. // Returns the address in expanded format with all zeroes included, like
  633. // 2001:db8:8:66:0:0:0:1
  634. //
  635. // Deprecated: use toFixedLengthString() instead.
  636. IPv6.prototype.toNormalizedString = function () {
  637. const addr = ((function () {
  638. const results = [];
  639. for (let i = 0; i < this.parts.length; i++) {
  640. results.push(this.parts[i].toString(16));
  641. }
  642. return results;
  643. }).call(this)).join(':');
  644. let suffix = '';
  645. if (this.zoneId) {
  646. suffix = `%${this.zoneId}`;
  647. }
  648. return addr + suffix;
  649. };
  650. // Returns the address in compact, human-readable format like
  651. // 2001:db8:8:66::1
  652. // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)
  653. IPv6.prototype.toRFC5952String = function () {
  654. const regex = /((^|:)(0(:|$)){2,})/g;
  655. const string = this.toNormalizedString();
  656. let bestMatchIndex = 0;
  657. let bestMatchLength = -1;
  658. let match;
  659. while ((match = regex.exec(string))) {
  660. if (match[0].length > bestMatchLength) {
  661. bestMatchIndex = match.index;
  662. bestMatchLength = match[0].length;
  663. }
  664. }
  665. if (bestMatchLength < 0) {
  666. return string;
  667. }
  668. return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;
  669. };
  670. // Returns the address in compact, human-readable format like
  671. // 2001:db8:8:66::1
  672. // Calls toRFC5952String under the hood.
  673. IPv6.prototype.toString = function () {
  674. return this.toRFC5952String();
  675. };
  676. return IPv6;
  677. })();
  678. // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation
  679. ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {
  680. try {
  681. const cidr = this.parseCIDR(string);
  682. const ipInterfaceOctets = cidr[0].toByteArray();
  683. const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  684. const octets = [];
  685. let i = 0;
  686. while (i < 16) {
  687. // Broadcast address is bitwise OR between ip interface and inverted mask
  688. octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
  689. i++;
  690. }
  691. return new this(octets);
  692. } catch (e) {
  693. throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);
  694. }
  695. };
  696. // Checks if a given string is formatted like IPv6 address.
  697. ipaddr.IPv6.isIPv6 = function (string) {
  698. return this.parser(string) !== null;
  699. };
  700. // Checks to see if string is a valid IPv6 Address
  701. ipaddr.IPv6.isValid = function (string) {
  702. // Since IPv6.isValid is always called first, this shortcut
  703. // provides a substantial performance gain.
  704. if (typeof string === 'string' && string.indexOf(':') === -1) {
  705. return false;
  706. }
  707. try {
  708. const addr = this.parser(string);
  709. new this(addr.parts, addr.zoneId);
  710. return true;
  711. } catch (e) {
  712. return false;
  713. }
  714. };
  715. // Checks if a given string is a valid IPv6 address in CIDR notation.
  716. ipaddr.IPv6.isValidCIDR = function (string) {
  717. // See note in IPv6.isValid
  718. if (typeof string === 'string' && string.indexOf(':') === -1) {
  719. return false;
  720. }
  721. try {
  722. this.parseCIDR(string);
  723. return true;
  724. } catch (e) {
  725. return false;
  726. }
  727. };
  728. // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation
  729. ipaddr.IPv6.networkAddressFromCIDR = function (string) {
  730. let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
  731. try {
  732. cidr = this.parseCIDR(string);
  733. ipInterfaceOctets = cidr[0].toByteArray();
  734. subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  735. octets = [];
  736. i = 0;
  737. while (i < 16) {
  738. // Network address is bitwise AND between ip interface and mask
  739. octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
  740. i++;
  741. }
  742. return new this(octets);
  743. } catch (e) {
  744. throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);
  745. }
  746. };
  747. // Tries to parse and validate a string with IPv6 address.
  748. // Throws an error if it fails.
  749. ipaddr.IPv6.parse = function (string) {
  750. const addr = this.parser(string);
  751. if (addr.parts === null) {
  752. throw new Error('ipaddr: string is not formatted like an IPv6 Address');
  753. }
  754. return new this(addr.parts, addr.zoneId);
  755. };
  756. ipaddr.IPv6.parseCIDR = function (string) {
  757. let maskLength, match, parsed;
  758. if ((match = string.match(/^(.+)\/(\d+)$/))) {
  759. maskLength = parseInt(match[2]);
  760. if (maskLength >= 0 && maskLength <= 128) {
  761. parsed = [this.parse(match[1]), maskLength];
  762. Object.defineProperty(parsed, 'toString', {
  763. value: function () {
  764. return this.join('/');
  765. }
  766. });
  767. return parsed;
  768. }
  769. }
  770. throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');
  771. };
  772. // Parse an IPv6 address.
  773. ipaddr.IPv6.parser = function (string) {
  774. let addr, i, match, octet, octets, zoneId;
  775. if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {
  776. return this.parser(`::ffff:${match[1]}`);
  777. }
  778. if (ipv6Regexes.native.test(string)) {
  779. return expandIPv6(string, 8);
  780. }
  781. if ((match = string.match(ipv6Regexes.transitional))) {
  782. zoneId = match[6] || '';
  783. addr = match[1]
  784. if (!match[1].endsWith('::')) {
  785. addr = addr.slice(0, -1)
  786. }
  787. addr = expandIPv6(addr + zoneId, 6);
  788. if (addr.parts) {
  789. octets = [
  790. parseInt(match[2]),
  791. parseInt(match[3]),
  792. parseInt(match[4]),
  793. parseInt(match[5])
  794. ];
  795. for (i = 0; i < octets.length; i++) {
  796. octet = octets[i];
  797. if (!((0 <= octet && octet <= 255))) {
  798. return null;
  799. }
  800. }
  801. addr.parts.push(octets[0] << 8 | octets[1]);
  802. addr.parts.push(octets[2] << 8 | octets[3]);
  803. return {
  804. parts: addr.parts,
  805. zoneId: addr.zoneId
  806. };
  807. }
  808. }
  809. return null;
  810. };
  811. // A utility function to return subnet mask in IPv6 format given the prefix length
  812. ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {
  813. prefix = parseInt(prefix);
  814. if (prefix < 0 || prefix > 128) {
  815. throw new Error('ipaddr: invalid IPv6 prefix length');
  816. }
  817. const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  818. let j = 0;
  819. const filledOctetCount = Math.floor(prefix / 8);
  820. while (j < filledOctetCount) {
  821. octets[j] = 255;
  822. j++;
  823. }
  824. if (filledOctetCount < 16) {
  825. octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
  826. }
  827. return new this(octets);
  828. };
  829. // Try to parse an array in network order (MSB first) for IPv4 and IPv6
  830. ipaddr.fromByteArray = function (bytes) {
  831. const length = bytes.length;
  832. if (length === 4) {
  833. return new ipaddr.IPv4(bytes);
  834. } else if (length === 16) {
  835. return new ipaddr.IPv6(bytes);
  836. } else {
  837. throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');
  838. }
  839. };
  840. // Checks if the address is valid IP address
  841. ipaddr.isValid = function (string) {
  842. return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
  843. };
  844. // Checks if the address is valid IP address in CIDR notation
  845. ipaddr.isValidCIDR = function (string) {
  846. return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);
  847. };
  848. // Attempts to parse an IP Address, first through IPv6 then IPv4.
  849. // Throws an error if it could not be parsed.
  850. ipaddr.parse = function (string) {
  851. if (ipaddr.IPv6.isValid(string)) {
  852. return ipaddr.IPv6.parse(string);
  853. } else if (ipaddr.IPv4.isValid(string)) {
  854. return ipaddr.IPv4.parse(string);
  855. } else {
  856. throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');
  857. }
  858. };
  859. // Attempt to parse CIDR notation, first through IPv6 then IPv4.
  860. // Throws an error if it could not be parsed.
  861. ipaddr.parseCIDR = function (string) {
  862. try {
  863. return ipaddr.IPv6.parseCIDR(string);
  864. } catch (e) {
  865. try {
  866. return ipaddr.IPv4.parseCIDR(string);
  867. } catch (e2) {
  868. throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');
  869. }
  870. }
  871. };
  872. // Parse an address and return plain IPv4 address if it is an IPv4-mapped address
  873. ipaddr.process = function (string) {
  874. const addr = this.parse(string);
  875. if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
  876. return addr.toIPv4Address();
  877. } else {
  878. return addr;
  879. }
  880. };
  881. // An utility function to ease named range matching. See examples below.
  882. // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors
  883. // on matching IPv4 addresses to IPv6 ranges or vice versa.
  884. ipaddr.subnetMatch = function (address, rangeList, defaultName) {
  885. let i, rangeName, rangeSubnets, subnet;
  886. if (defaultName === undefined || defaultName === null) {
  887. defaultName = 'unicast';
  888. }
  889. for (rangeName in rangeList) {
  890. if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {
  891. rangeSubnets = rangeList[rangeName];
  892. // ECMA5 Array.isArray isn't available everywhere
  893. if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
  894. rangeSubnets = [rangeSubnets];
  895. }
  896. for (i = 0; i < rangeSubnets.length; i++) {
  897. subnet = rangeSubnets[i];
  898. if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {
  899. return rangeName;
  900. }
  901. }
  902. }
  903. }
  904. return defaultName;
  905. };
  906. // Export for both the CommonJS and browser-like environment
  907. if (typeof module !== 'undefined' && module.exports) {
  908. module.exports = ipaddr;
  909. } else {
  910. root.ipaddr = ipaddr;
  911. }
  912. }(this));