ipaddr.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. (function() {
  2. var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root;
  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 rangeName, rangeSubnets, subnet, _i, _len;
  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 (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) {
  40. subnet = rangeSubnets[_i];
  41. if (address.match.apply(address, subnet)) {
  42. return rangeName;
  43. }
  44. }
  45. }
  46. return defaultName;
  47. };
  48. ipaddr.IPv4 = (function() {
  49. function IPv4(octets) {
  50. var octet, _i, _len;
  51. if (octets.length !== 4) {
  52. throw new Error("ipaddr: ipv4 octet count should be 4");
  53. }
  54. for (_i = 0, _len = octets.length; _i < _len; _i++) {
  55. octet = octets[_i];
  56. if (!((0 <= octet && octet <= 255))) {
  57. throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
  58. }
  59. }
  60. this.octets = octets;
  61. }
  62. IPv4.prototype.kind = function() {
  63. return 'ipv4';
  64. };
  65. IPv4.prototype.toString = function() {
  66. return this.octets.join(".");
  67. };
  68. IPv4.prototype.toByteArray = function() {
  69. return this.octets.slice(0);
  70. };
  71. IPv4.prototype.match = function(other, cidrRange) {
  72. var _ref;
  73. if (cidrRange === void 0) {
  74. _ref = other, other = _ref[0], cidrRange = _ref[1];
  75. }
  76. if (other.kind() !== 'ipv4') {
  77. throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
  78. }
  79. return matchCIDR(this.octets, other.octets, 8, cidrRange);
  80. };
  81. IPv4.prototype.SpecialRanges = {
  82. unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
  83. broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
  84. multicast: [[new IPv4([224, 0, 0, 0]), 4]],
  85. linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
  86. loopback: [[new IPv4([127, 0, 0, 0]), 8]],
  87. "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
  88. 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]]
  89. };
  90. IPv4.prototype.range = function() {
  91. return ipaddr.subnetMatch(this, this.SpecialRanges);
  92. };
  93. IPv4.prototype.toIPv4MappedAddress = function() {
  94. return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
  95. };
  96. IPv4.prototype.prefixLengthFromSubnetMask = function() {
  97. var cidr, i, octet, stop, zeros, zerotable, _i;
  98. zerotable = {
  99. 0: 8,
  100. 128: 7,
  101. 192: 6,
  102. 224: 5,
  103. 240: 4,
  104. 248: 3,
  105. 252: 2,
  106. 254: 1,
  107. 255: 0
  108. };
  109. cidr = 0;
  110. stop = false;
  111. for (i = _i = 3; _i >= 0; i = _i += -1) {
  112. octet = this.octets[i];
  113. if (octet in zerotable) {
  114. zeros = zerotable[octet];
  115. if (stop && zeros !== 0) {
  116. return null;
  117. }
  118. if (zeros !== 8) {
  119. stop = true;
  120. }
  121. cidr += zeros;
  122. } else {
  123. return null;
  124. }
  125. }
  126. return 32 - cidr;
  127. };
  128. return IPv4;
  129. })();
  130. ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
  131. ipv4Regexes = {
  132. fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
  133. longValue: new RegExp("^" + ipv4Part + "$", 'i')
  134. };
  135. ipaddr.IPv4.parser = function(string) {
  136. var match, parseIntAuto, part, shift, value;
  137. parseIntAuto = function(string) {
  138. if (string[0] === "0" && string[1] !== "x") {
  139. return parseInt(string, 8);
  140. } else {
  141. return parseInt(string);
  142. }
  143. };
  144. if (match = string.match(ipv4Regexes.fourOctet)) {
  145. return (function() {
  146. var _i, _len, _ref, _results;
  147. _ref = match.slice(1, 6);
  148. _results = [];
  149. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  150. part = _ref[_i];
  151. _results.push(parseIntAuto(part));
  152. }
  153. return _results;
  154. })();
  155. } else if (match = string.match(ipv4Regexes.longValue)) {
  156. value = parseIntAuto(match[1]);
  157. if (value > 0xffffffff || value < 0) {
  158. throw new Error("ipaddr: address outside defined range");
  159. }
  160. return ((function() {
  161. var _i, _results;
  162. _results = [];
  163. for (shift = _i = 0; _i <= 24; shift = _i += 8) {
  164. _results.push((value >> shift) & 0xff);
  165. }
  166. return _results;
  167. })()).reverse();
  168. } else {
  169. return null;
  170. }
  171. };
  172. ipaddr.IPv6 = (function() {
  173. function IPv6(parts) {
  174. var i, part, _i, _j, _len, _ref;
  175. if (parts.length === 16) {
  176. this.parts = [];
  177. for (i = _i = 0; _i <= 14; i = _i += 2) {
  178. this.parts.push((parts[i] << 8) | parts[i + 1]);
  179. }
  180. } else if (parts.length === 8) {
  181. this.parts = parts;
  182. } else {
  183. throw new Error("ipaddr: ipv6 part count should be 8 or 16");
  184. }
  185. _ref = this.parts;
  186. for (_j = 0, _len = _ref.length; _j < _len; _j++) {
  187. part = _ref[_j];
  188. if (!((0 <= part && part <= 0xffff))) {
  189. throw new Error("ipaddr: ipv6 part should fit in 16 bits");
  190. }
  191. }
  192. }
  193. IPv6.prototype.kind = function() {
  194. return 'ipv6';
  195. };
  196. IPv6.prototype.toString = function() {
  197. var compactStringParts, part, pushPart, state, stringParts, _i, _len;
  198. stringParts = (function() {
  199. var _i, _len, _ref, _results;
  200. _ref = this.parts;
  201. _results = [];
  202. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  203. part = _ref[_i];
  204. _results.push(part.toString(16));
  205. }
  206. return _results;
  207. }).call(this);
  208. compactStringParts = [];
  209. pushPart = function(part) {
  210. return compactStringParts.push(part);
  211. };
  212. state = 0;
  213. for (_i = 0, _len = stringParts.length; _i < _len; _i++) {
  214. part = stringParts[_i];
  215. switch (state) {
  216. case 0:
  217. if (part === '0') {
  218. pushPart('');
  219. } else {
  220. pushPart(part);
  221. }
  222. state = 1;
  223. break;
  224. case 1:
  225. if (part === '0') {
  226. state = 2;
  227. } else {
  228. pushPart(part);
  229. }
  230. break;
  231. case 2:
  232. if (part !== '0') {
  233. pushPart('');
  234. pushPart(part);
  235. state = 3;
  236. }
  237. break;
  238. case 3:
  239. pushPart(part);
  240. }
  241. }
  242. if (state === 2) {
  243. pushPart('');
  244. pushPart('');
  245. }
  246. return compactStringParts.join(":");
  247. };
  248. IPv6.prototype.toByteArray = function() {
  249. var bytes, part, _i, _len, _ref;
  250. bytes = [];
  251. _ref = this.parts;
  252. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  253. part = _ref[_i];
  254. bytes.push(part >> 8);
  255. bytes.push(part & 0xff);
  256. }
  257. return bytes;
  258. };
  259. IPv6.prototype.toNormalizedString = function() {
  260. var part;
  261. return ((function() {
  262. var _i, _len, _ref, _results;
  263. _ref = this.parts;
  264. _results = [];
  265. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  266. part = _ref[_i];
  267. _results.push(part.toString(16));
  268. }
  269. return _results;
  270. }).call(this)).join(":");
  271. };
  272. IPv6.prototype.match = function(other, cidrRange) {
  273. var _ref;
  274. if (cidrRange === void 0) {
  275. _ref = other, other = _ref[0], cidrRange = _ref[1];
  276. }
  277. if (other.kind() !== 'ipv6') {
  278. throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
  279. }
  280. return matchCIDR(this.parts, other.parts, 16, cidrRange);
  281. };
  282. IPv6.prototype.SpecialRanges = {
  283. unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
  284. linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
  285. multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
  286. loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
  287. uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
  288. ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
  289. rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
  290. rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
  291. '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
  292. teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
  293. reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
  294. };
  295. IPv6.prototype.range = function() {
  296. return ipaddr.subnetMatch(this, this.SpecialRanges);
  297. };
  298. IPv6.prototype.isIPv4MappedAddress = function() {
  299. return this.range() === 'ipv4Mapped';
  300. };
  301. IPv6.prototype.toIPv4Address = function() {
  302. var high, low, _ref;
  303. if (!this.isIPv4MappedAddress()) {
  304. throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
  305. }
  306. _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1];
  307. return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
  308. };
  309. return IPv6;
  310. })();
  311. ipv6Part = "(?:[0-9a-f]+::?)+";
  312. ipv6Regexes = {
  313. "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'),
  314. transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i')
  315. };
  316. expandIPv6 = function(string, parts) {
  317. var colonCount, lastColon, part, replacement, replacementCount;
  318. if (string.indexOf('::') !== string.lastIndexOf('::')) {
  319. return null;
  320. }
  321. colonCount = 0;
  322. lastColon = -1;
  323. while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
  324. colonCount++;
  325. }
  326. if (string.substr(0, 2) === '::') {
  327. colonCount--;
  328. }
  329. if (string.substr(-2, 2) === '::') {
  330. colonCount--;
  331. }
  332. if (colonCount > parts) {
  333. return null;
  334. }
  335. replacementCount = parts - colonCount;
  336. replacement = ':';
  337. while (replacementCount--) {
  338. replacement += '0:';
  339. }
  340. string = string.replace('::', replacement);
  341. if (string[0] === ':') {
  342. string = string.slice(1);
  343. }
  344. if (string[string.length - 1] === ':') {
  345. string = string.slice(0, -1);
  346. }
  347. return (function() {
  348. var _i, _len, _ref, _results;
  349. _ref = string.split(":");
  350. _results = [];
  351. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  352. part = _ref[_i];
  353. _results.push(parseInt(part, 16));
  354. }
  355. return _results;
  356. })();
  357. };
  358. ipaddr.IPv6.parser = function(string) {
  359. var match, octet, octets, parts, _i, _len;
  360. if (string.match(ipv6Regexes['native'])) {
  361. return expandIPv6(string, 8);
  362. } else if (match = string.match(ipv6Regexes['transitional'])) {
  363. parts = expandIPv6(match[1].slice(0, -1), 6);
  364. if (parts) {
  365. octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
  366. for (_i = 0, _len = octets.length; _i < _len; _i++) {
  367. octet = octets[_i];
  368. if (!((0 <= octet && octet <= 255))) {
  369. return null;
  370. }
  371. }
  372. parts.push(octets[0] << 8 | octets[1]);
  373. parts.push(octets[2] << 8 | octets[3]);
  374. return parts;
  375. }
  376. }
  377. return null;
  378. };
  379. ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
  380. return this.parser(string) !== null;
  381. };
  382. ipaddr.IPv4.isValid = function(string) {
  383. var e;
  384. try {
  385. new this(this.parser(string));
  386. return true;
  387. } catch (_error) {
  388. e = _error;
  389. return false;
  390. }
  391. };
  392. ipaddr.IPv4.isValidFourPartDecimal = function(string) {
  393. if (ipaddr.IPv4.isValid(string) && string.match(/^\d+(\.\d+){3}$/)) {
  394. return true;
  395. } else {
  396. return false;
  397. }
  398. };
  399. ipaddr.IPv6.isValid = function(string) {
  400. var e;
  401. if (typeof string === "string" && string.indexOf(":") === -1) {
  402. return false;
  403. }
  404. try {
  405. new this(this.parser(string));
  406. return true;
  407. } catch (_error) {
  408. e = _error;
  409. return false;
  410. }
  411. };
  412. ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) {
  413. var parts;
  414. parts = this.parser(string);
  415. if (parts === null) {
  416. throw new Error("ipaddr: string is not formatted like ip address");
  417. }
  418. return new this(parts);
  419. };
  420. ipaddr.IPv4.parseCIDR = function(string) {
  421. var maskLength, match;
  422. if (match = string.match(/^(.+)\/(\d+)$/)) {
  423. maskLength = parseInt(match[2]);
  424. if (maskLength >= 0 && maskLength <= 32) {
  425. return [this.parse(match[1]), maskLength];
  426. }
  427. }
  428. throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
  429. };
  430. ipaddr.IPv6.parseCIDR = function(string) {
  431. var maskLength, match;
  432. if (match = string.match(/^(.+)\/(\d+)$/)) {
  433. maskLength = parseInt(match[2]);
  434. if (maskLength >= 0 && maskLength <= 128) {
  435. return [this.parse(match[1]), maskLength];
  436. }
  437. }
  438. throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
  439. };
  440. ipaddr.isValid = function(string) {
  441. return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
  442. };
  443. ipaddr.parse = function(string) {
  444. if (ipaddr.IPv6.isValid(string)) {
  445. return ipaddr.IPv6.parse(string);
  446. } else if (ipaddr.IPv4.isValid(string)) {
  447. return ipaddr.IPv4.parse(string);
  448. } else {
  449. throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
  450. }
  451. };
  452. ipaddr.parseCIDR = function(string) {
  453. var e;
  454. try {
  455. return ipaddr.IPv6.parseCIDR(string);
  456. } catch (_error) {
  457. e = _error;
  458. try {
  459. return ipaddr.IPv4.parseCIDR(string);
  460. } catch (_error) {
  461. e = _error;
  462. throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
  463. }
  464. }
  465. };
  466. ipaddr.fromByteArray = function(bytes) {
  467. var length;
  468. length = bytes.length;
  469. if (length === 4) {
  470. return new ipaddr.IPv4(bytes);
  471. } else if (length === 16) {
  472. return new ipaddr.IPv6(bytes);
  473. } else {
  474. throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
  475. }
  476. };
  477. ipaddr.process = function(string) {
  478. var addr;
  479. addr = this.parse(string);
  480. if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
  481. return addr.toIPv4Address();
  482. } else {
  483. return addr;
  484. }
  485. };
  486. }).call(this);