ipaddr.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. (function() {
  2. var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex;
  3. ipaddr = {};
  4. root = this;
  5. if ((typeof module !== "undefined" && module !== null) && module.exports) {
  6. module.exports = ipaddr;
  7. } else {
  8. root['ipaddr'] = ipaddr;
  9. }
  10. matchCIDR = function(first, second, partSize, cidrBits) {
  11. var part, shift;
  12. if (first.length !== second.length) {
  13. throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
  14. }
  15. part = 0;
  16. while (cidrBits > 0) {
  17. shift = partSize - cidrBits;
  18. if (shift < 0) {
  19. shift = 0;
  20. }
  21. if (first[part] >> shift !== second[part] >> shift) {
  22. return false;
  23. }
  24. cidrBits -= partSize;
  25. part += 1;
  26. }
  27. return true;
  28. };
  29. ipaddr.subnetMatch = function(address, rangeList, defaultName) {
  30. var k, len, rangeName, rangeSubnets, subnet;
  31. if (defaultName == null) {
  32. defaultName = 'unicast';
  33. }
  34. for (rangeName in rangeList) {
  35. rangeSubnets = rangeList[rangeName];
  36. if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
  37. rangeSubnets = [rangeSubnets];
  38. }
  39. for (k = 0, len = rangeSubnets.length; k < len; k++) {
  40. subnet = rangeSubnets[k];
  41. if (address.kind() === subnet[0].kind()) {
  42. if (address.match.apply(address, subnet)) {
  43. return rangeName;
  44. }
  45. }
  46. }
  47. }
  48. return defaultName;
  49. };
  50. ipaddr.IPv4 = (function() {
  51. function IPv4(octets) {
  52. var k, len, octet;
  53. if (octets.length !== 4) {
  54. throw new Error("ipaddr: ipv4 octet count should be 4");
  55. }
  56. for (k = 0, len = octets.length; k < len; k++) {
  57. octet = octets[k];
  58. if (!((0 <= octet && octet <= 255))) {
  59. throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
  60. }
  61. }
  62. this.octets = octets;
  63. }
  64. IPv4.prototype.kind = function() {
  65. return 'ipv4';
  66. };
  67. IPv4.prototype.toString = function() {
  68. return this.octets.join(".");
  69. };
  70. IPv4.prototype.toNormalizedString = function() {
  71. return this.toString();
  72. };
  73. IPv4.prototype.toByteArray = function() {
  74. return this.octets.slice(0);
  75. };
  76. IPv4.prototype.match = function(other, cidrRange) {
  77. var ref;
  78. if (cidrRange === void 0) {
  79. ref = other, other = ref[0], cidrRange = ref[1];
  80. }
  81. if (other.kind() !== 'ipv4') {
  82. throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
  83. }
  84. return matchCIDR(this.octets, other.octets, 8, cidrRange);
  85. };
  86. IPv4.prototype.SpecialRanges = {
  87. unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
  88. broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
  89. multicast: [[new IPv4([224, 0, 0, 0]), 4]],
  90. linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
  91. loopback: [[new IPv4([127, 0, 0, 0]), 8]],
  92. carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
  93. "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
  94. reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
  95. };
  96. IPv4.prototype.range = function() {
  97. return ipaddr.subnetMatch(this, this.SpecialRanges);
  98. };
  99. IPv4.prototype.toIPv4MappedAddress = function() {
  100. return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
  101. };
  102. IPv4.prototype.prefixLengthFromSubnetMask = function() {
  103. var cidr, i, k, octet, stop, zeros, zerotable;
  104. zerotable = {
  105. 0: 8,
  106. 128: 7,
  107. 192: 6,
  108. 224: 5,
  109. 240: 4,
  110. 248: 3,
  111. 252: 2,
  112. 254: 1,
  113. 255: 0
  114. };
  115. cidr = 0;
  116. stop = false;
  117. for (i = k = 3; k >= 0; i = k += -1) {
  118. octet = this.octets[i];
  119. if (octet in zerotable) {
  120. zeros = zerotable[octet];
  121. if (stop && zeros !== 0) {
  122. return null;
  123. }
  124. if (zeros !== 8) {
  125. stop = true;
  126. }
  127. cidr += zeros;
  128. } else {
  129. return null;
  130. }
  131. }
  132. return 32 - cidr;
  133. };
  134. return IPv4;
  135. })();
  136. ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
  137. ipv4Regexes = {
  138. fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
  139. longValue: new RegExp("^" + ipv4Part + "$", 'i')
  140. };
  141. ipaddr.IPv4.parser = function(string) {
  142. var match, parseIntAuto, part, shift, value;
  143. parseIntAuto = function(string) {
  144. if (string[0] === "0" && string[1] !== "x") {
  145. return parseInt(string, 8);
  146. } else {
  147. return parseInt(string);
  148. }
  149. };
  150. if (match = string.match(ipv4Regexes.fourOctet)) {
  151. return (function() {
  152. var k, len, ref, results;
  153. ref = match.slice(1, 6);
  154. results = [];
  155. for (k = 0, len = ref.length; k < len; k++) {
  156. part = ref[k];
  157. results.push(parseIntAuto(part));
  158. }
  159. return results;
  160. })();
  161. } else if (match = string.match(ipv4Regexes.longValue)) {
  162. value = parseIntAuto(match[1]);
  163. if (value > 0xffffffff || value < 0) {
  164. throw new Error("ipaddr: address outside defined range");
  165. }
  166. return ((function() {
  167. var k, results;
  168. results = [];
  169. for (shift = k = 0; k <= 24; shift = k += 8) {
  170. results.push((value >> shift) & 0xff);
  171. }
  172. return results;
  173. })()).reverse();
  174. } else {
  175. return null;
  176. }
  177. };
  178. ipaddr.IPv6 = (function() {
  179. function IPv6(parts, zoneId) {
  180. var i, k, l, len, part, ref;
  181. if (parts.length === 16) {
  182. this.parts = [];
  183. for (i = k = 0; k <= 14; i = k += 2) {
  184. this.parts.push((parts[i] << 8) | parts[i + 1]);
  185. }
  186. } else if (parts.length === 8) {
  187. this.parts = parts;
  188. } else {
  189. throw new Error("ipaddr: ipv6 part count should be 8 or 16");
  190. }
  191. ref = this.parts;
  192. for (l = 0, len = ref.length; l < len; l++) {
  193. part = ref[l];
  194. if (!((0 <= part && part <= 0xffff))) {
  195. throw new Error("ipaddr: ipv6 part should fit in 16 bits");
  196. }
  197. }
  198. if (zoneId) {
  199. this.zoneId = zoneId;
  200. }
  201. }
  202. IPv6.prototype.kind = function() {
  203. return 'ipv6';
  204. };
  205. IPv6.prototype.toString = function() {
  206. return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::');
  207. };
  208. IPv6.prototype.toByteArray = function() {
  209. var bytes, k, len, part, ref;
  210. bytes = [];
  211. ref = this.parts;
  212. for (k = 0, len = ref.length; k < len; k++) {
  213. part = ref[k];
  214. bytes.push(part >> 8);
  215. bytes.push(part & 0xff);
  216. }
  217. return bytes;
  218. };
  219. IPv6.prototype.toNormalizedString = function() {
  220. var addr, part, suffix;
  221. addr = ((function() {
  222. var k, len, ref, results;
  223. ref = this.parts;
  224. results = [];
  225. for (k = 0, len = ref.length; k < len; k++) {
  226. part = ref[k];
  227. results.push(part.toString(16));
  228. }
  229. return results;
  230. }).call(this)).join(":");
  231. suffix = '';
  232. if (this.zoneId) {
  233. suffix = '%' + this.zoneId;
  234. }
  235. return addr + suffix;
  236. };
  237. IPv6.prototype.match = function(other, cidrRange) {
  238. var ref;
  239. if (cidrRange === void 0) {
  240. ref = other, other = ref[0], cidrRange = ref[1];
  241. }
  242. if (other.kind() !== 'ipv6') {
  243. throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
  244. }
  245. return matchCIDR(this.parts, other.parts, 16, cidrRange);
  246. };
  247. IPv6.prototype.SpecialRanges = {
  248. unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
  249. linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
  250. multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
  251. loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
  252. uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
  253. ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
  254. rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
  255. rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
  256. '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
  257. teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
  258. reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
  259. };
  260. IPv6.prototype.range = function() {
  261. return ipaddr.subnetMatch(this, this.SpecialRanges);
  262. };
  263. IPv6.prototype.isIPv4MappedAddress = function() {
  264. return this.range() === 'ipv4Mapped';
  265. };
  266. IPv6.prototype.toIPv4Address = function() {
  267. var high, low, ref;
  268. if (!this.isIPv4MappedAddress()) {
  269. throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
  270. }
  271. ref = this.parts.slice(-2), high = ref[0], low = ref[1];
  272. return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
  273. };
  274. IPv6.prototype.prefixLengthFromSubnetMask = function() {
  275. var cidr, i, k, part, stop, zeros, zerotable;
  276. zerotable = {
  277. 0: 16,
  278. 32768: 15,
  279. 49152: 14,
  280. 57344: 13,
  281. 61440: 12,
  282. 63488: 11,
  283. 64512: 10,
  284. 65024: 9,
  285. 65280: 8,
  286. 65408: 7,
  287. 65472: 6,
  288. 65504: 5,
  289. 65520: 4,
  290. 65528: 3,
  291. 65532: 2,
  292. 65534: 1,
  293. 65535: 0
  294. };
  295. cidr = 0;
  296. stop = false;
  297. for (i = k = 7; k >= 0; i = k += -1) {
  298. part = this.parts[i];
  299. if (part in zerotable) {
  300. zeros = zerotable[part];
  301. if (stop && zeros !== 0) {
  302. return null;
  303. }
  304. if (zeros !== 16) {
  305. stop = true;
  306. }
  307. cidr += zeros;
  308. } else {
  309. return null;
  310. }
  311. }
  312. return 128 - cidr;
  313. };
  314. return IPv6;
  315. })();
  316. ipv6Part = "(?:[0-9a-f]+::?)+";
  317. zoneIndex = "%[0-9a-z]{1,}";
  318. ipv6Regexes = {
  319. zoneIndex: new RegExp(zoneIndex, 'i'),
  320. "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'),
  321. transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i')
  322. };
  323. expandIPv6 = function(string, parts) {
  324. var colonCount, lastColon, part, replacement, replacementCount, zoneId;
  325. if (string.indexOf('::') !== string.lastIndexOf('::')) {
  326. return null;
  327. }
  328. zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0];
  329. if (zoneId) {
  330. zoneId = zoneId.substring(1);
  331. string = string.replace(/%.+$/, '');
  332. }
  333. colonCount = 0;
  334. lastColon = -1;
  335. while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
  336. colonCount++;
  337. }
  338. if (string.substr(0, 2) === '::') {
  339. colonCount--;
  340. }
  341. if (string.substr(-2, 2) === '::') {
  342. colonCount--;
  343. }
  344. if (colonCount > parts) {
  345. return null;
  346. }
  347. replacementCount = parts - colonCount;
  348. replacement = ':';
  349. while (replacementCount--) {
  350. replacement += '0:';
  351. }
  352. string = string.replace('::', replacement);
  353. if (string[0] === ':') {
  354. string = string.slice(1);
  355. }
  356. if (string[string.length - 1] === ':') {
  357. string = string.slice(0, -1);
  358. }
  359. parts = (function() {
  360. var k, len, ref, results;
  361. ref = string.split(":");
  362. results = [];
  363. for (k = 0, len = ref.length; k < len; k++) {
  364. part = ref[k];
  365. results.push(parseInt(part, 16));
  366. }
  367. return results;
  368. })();
  369. return {
  370. parts: parts,
  371. zoneId: zoneId
  372. };
  373. };
  374. ipaddr.IPv6.parser = function(string) {
  375. var addr, k, len, match, octet, octets, zoneId;
  376. if (ipv6Regexes['native'].test(string)) {
  377. return expandIPv6(string, 8);
  378. } else if (match = string.match(ipv6Regexes['transitional'])) {
  379. zoneId = match[6] || '';
  380. addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
  381. if (addr.parts) {
  382. octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
  383. for (k = 0, len = octets.length; k < len; k++) {
  384. octet = octets[k];
  385. if (!((0 <= octet && octet <= 255))) {
  386. return null;
  387. }
  388. }
  389. addr.parts.push(octets[0] << 8 | octets[1]);
  390. addr.parts.push(octets[2] << 8 | octets[3]);
  391. return {
  392. parts: addr.parts,
  393. zoneId: addr.zoneId
  394. };
  395. }
  396. }
  397. return null;
  398. };
  399. ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
  400. return this.parser(string) !== null;
  401. };
  402. ipaddr.IPv4.isValid = function(string) {
  403. var e;
  404. try {
  405. new this(this.parser(string));
  406. return true;
  407. } catch (error1) {
  408. e = error1;
  409. return false;
  410. }
  411. };
  412. ipaddr.IPv4.isValidFourPartDecimal = function(string) {
  413. if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
  414. return true;
  415. } else {
  416. return false;
  417. }
  418. };
  419. ipaddr.IPv6.isValid = function(string) {
  420. var addr, e;
  421. if (typeof string === "string" && string.indexOf(":") === -1) {
  422. return false;
  423. }
  424. try {
  425. addr = this.parser(string);
  426. new this(addr.parts, addr.zoneId);
  427. return true;
  428. } catch (error1) {
  429. e = error1;
  430. return false;
  431. }
  432. };
  433. ipaddr.IPv4.parse = function(string) {
  434. var parts;
  435. parts = this.parser(string);
  436. if (parts === null) {
  437. throw new Error("ipaddr: string is not formatted like ip address");
  438. }
  439. return new this(parts);
  440. };
  441. ipaddr.IPv6.parse = function(string) {
  442. var addr;
  443. addr = this.parser(string);
  444. if (addr.parts === null) {
  445. throw new Error("ipaddr: string is not formatted like ip address");
  446. }
  447. return new this(addr.parts, addr.zoneId);
  448. };
  449. ipaddr.IPv4.parseCIDR = function(string) {
  450. var maskLength, match, parsed;
  451. if (match = string.match(/^(.+)\/(\d+)$/)) {
  452. maskLength = parseInt(match[2]);
  453. if (maskLength >= 0 && maskLength <= 32) {
  454. parsed = [this.parse(match[1]), maskLength];
  455. Object.defineProperty(parsed, 'toString', {
  456. value: function() {
  457. return this.join('/');
  458. }
  459. });
  460. return parsed;
  461. }
  462. }
  463. throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
  464. };
  465. ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
  466. var filledOctetCount, j, octets;
  467. prefix = parseInt(prefix);
  468. if (prefix < 0 || prefix > 32) {
  469. throw new Error('ipaddr: invalid IPv4 prefix length');
  470. }
  471. octets = [0, 0, 0, 0];
  472. j = 0;
  473. filledOctetCount = Math.floor(prefix / 8);
  474. while (j < filledOctetCount) {
  475. octets[j] = 255;
  476. j++;
  477. }
  478. if (filledOctetCount < 4) {
  479. octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
  480. }
  481. return new this(octets);
  482. };
  483. ipaddr.IPv4.broadcastAddressFromCIDR = function(string) {
  484. var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
  485. try {
  486. cidr = this.parseCIDR(string);
  487. ipInterfaceOctets = cidr[0].toByteArray();
  488. subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  489. octets = [];
  490. i = 0;
  491. while (i < 4) {
  492. octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
  493. i++;
  494. }
  495. return new this(octets);
  496. } catch (error1) {
  497. error = error1;
  498. throw new Error('ipaddr: the address does not have IPv4 CIDR format');
  499. }
  500. };
  501. ipaddr.IPv4.networkAddressFromCIDR = function(string) {
  502. var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
  503. try {
  504. cidr = this.parseCIDR(string);
  505. ipInterfaceOctets = cidr[0].toByteArray();
  506. subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
  507. octets = [];
  508. i = 0;
  509. while (i < 4) {
  510. octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
  511. i++;
  512. }
  513. return new this(octets);
  514. } catch (error1) {
  515. error = error1;
  516. throw new Error('ipaddr: the address does not have IPv4 CIDR format');
  517. }
  518. };
  519. ipaddr.IPv6.parseCIDR = function(string) {
  520. var maskLength, match, parsed;
  521. if (match = string.match(/^(.+)\/(\d+)$/)) {
  522. maskLength = parseInt(match[2]);
  523. if (maskLength >= 0 && maskLength <= 128) {
  524. parsed = [this.parse(match[1]), maskLength];
  525. Object.defineProperty(parsed, 'toString', {
  526. value: function() {
  527. return this.join('/');
  528. }
  529. });
  530. return parsed;
  531. }
  532. }
  533. throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
  534. };
  535. ipaddr.isValid = function(string) {
  536. return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
  537. };
  538. ipaddr.parse = function(string) {
  539. if (ipaddr.IPv6.isValid(string)) {
  540. return ipaddr.IPv6.parse(string);
  541. } else if (ipaddr.IPv4.isValid(string)) {
  542. return ipaddr.IPv4.parse(string);
  543. } else {
  544. throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
  545. }
  546. };
  547. ipaddr.parseCIDR = function(string) {
  548. var e;
  549. try {
  550. return ipaddr.IPv6.parseCIDR(string);
  551. } catch (error1) {
  552. e = error1;
  553. try {
  554. return ipaddr.IPv4.parseCIDR(string);
  555. } catch (error1) {
  556. e = error1;
  557. throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
  558. }
  559. }
  560. };
  561. ipaddr.fromByteArray = function(bytes) {
  562. var length;
  563. length = bytes.length;
  564. if (length === 4) {
  565. return new ipaddr.IPv4(bytes);
  566. } else if (length === 16) {
  567. return new ipaddr.IPv6(bytes);
  568. } else {
  569. throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
  570. }
  571. };
  572. ipaddr.process = function(string) {
  573. var addr;
  574. addr = this.parse(string);
  575. if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
  576. return addr.toIPv4Address();
  577. } else {
  578. return addr;
  579. }
  580. };
  581. }).call(this);