ipaddr.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 (toString.call(rangeSubnets[0]) !== '[object 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 is a byte");
  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. if (other.kind() !== 'ipv4') {
  73. throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
  74. }
  75. return matchCIDR(this.octets, other.octets, 8, cidrRange);
  76. };
  77. IPv4.prototype.SpecialRanges = {
  78. broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
  79. multicast: [[new IPv4([224, 0, 0, 0]), 4]],
  80. linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
  81. loopback: [[new IPv4([127, 0, 0, 0]), 8]],
  82. "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
  83. 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]]
  84. };
  85. IPv4.prototype.range = function() {
  86. return ipaddr.subnetMatch(this, this.SpecialRanges);
  87. };
  88. IPv4.prototype.toIPv4MappedAddress = function() {
  89. return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
  90. };
  91. return IPv4;
  92. })();
  93. ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
  94. ipv4Regexes = {
  95. fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
  96. longValue: new RegExp("^" + ipv4Part + "$", 'i')
  97. };
  98. ipaddr.IPv4.parser = function(string) {
  99. var match, parseIntAuto, part, shift, value;
  100. parseIntAuto = function(string) {
  101. if (string[0] === "0" && string[1] !== "x") {
  102. return parseInt(string, 8);
  103. } else {
  104. return parseInt(string);
  105. }
  106. };
  107. if (match = string.match(ipv4Regexes.fourOctet)) {
  108. return (function() {
  109. var _i, _len, _ref, _results;
  110. _ref = match.slice(1, 6);
  111. _results = [];
  112. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  113. part = _ref[_i];
  114. _results.push(parseIntAuto(part));
  115. }
  116. return _results;
  117. })();
  118. } else if (match = string.match(ipv4Regexes.longValue)) {
  119. value = parseIntAuto(match[1]);
  120. return ((function() {
  121. var _i, _results;
  122. _results = [];
  123. for (shift = _i = 0; _i <= 24; shift = _i += 8) {
  124. _results.push((value >> shift) & 0xff);
  125. }
  126. return _results;
  127. })()).reverse();
  128. } else {
  129. return null;
  130. }
  131. };
  132. ipaddr.IPv6 = (function() {
  133. function IPv6(parts) {
  134. var part, _i, _len;
  135. if (parts.length !== 8) {
  136. throw new Error("ipaddr: ipv6 part count should be 8");
  137. }
  138. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  139. part = parts[_i];
  140. if (!((0 <= part && part <= 0xffff))) {
  141. throw new Error("ipaddr: ipv6 part should fit to two octets");
  142. }
  143. }
  144. this.parts = parts;
  145. }
  146. IPv6.prototype.kind = function() {
  147. return 'ipv6';
  148. };
  149. IPv6.prototype.toString = function() {
  150. var compactStringParts, part, pushPart, state, stringParts, _i, _len;
  151. stringParts = (function() {
  152. var _i, _len, _ref, _results;
  153. _ref = this.parts;
  154. _results = [];
  155. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  156. part = _ref[_i];
  157. _results.push(part.toString(16));
  158. }
  159. return _results;
  160. }).call(this);
  161. compactStringParts = [];
  162. pushPart = function(part) {
  163. return compactStringParts.push(part);
  164. };
  165. state = 0;
  166. for (_i = 0, _len = stringParts.length; _i < _len; _i++) {
  167. part = stringParts[_i];
  168. switch (state) {
  169. case 0:
  170. if (part === '0') {
  171. pushPart('');
  172. } else {
  173. pushPart(part);
  174. }
  175. state = 1;
  176. break;
  177. case 1:
  178. if (part === '0') {
  179. state = 2;
  180. } else {
  181. pushPart(part);
  182. }
  183. break;
  184. case 2:
  185. if (part !== '0') {
  186. pushPart('');
  187. pushPart(part);
  188. state = 3;
  189. }
  190. break;
  191. case 3:
  192. pushPart(part);
  193. }
  194. }
  195. if (state === 2) {
  196. pushPart('');
  197. pushPart('');
  198. }
  199. return compactStringParts.join(":");
  200. };
  201. IPv6.prototype.toByteArray = function() {
  202. var bytes, part, _i, _len, _ref;
  203. bytes = [];
  204. _ref = this.parts;
  205. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  206. part = _ref[_i];
  207. bytes.push(part >> 8);
  208. bytes.push(part & 0xff);
  209. }
  210. return bytes;
  211. };
  212. IPv6.prototype.toNormalizedString = function() {
  213. var part;
  214. return ((function() {
  215. var _i, _len, _ref, _results;
  216. _ref = this.parts;
  217. _results = [];
  218. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  219. part = _ref[_i];
  220. _results.push(part.toString(16));
  221. }
  222. return _results;
  223. }).call(this)).join(":");
  224. };
  225. IPv6.prototype.match = function(other, cidrRange) {
  226. if (other.kind() !== 'ipv6') {
  227. throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
  228. }
  229. return matchCIDR(this.parts, other.parts, 16, cidrRange);
  230. };
  231. IPv6.prototype.SpecialRanges = {
  232. unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
  233. linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
  234. multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
  235. loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
  236. uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
  237. ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
  238. rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
  239. rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
  240. '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
  241. teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
  242. reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
  243. };
  244. IPv6.prototype.range = function() {
  245. return ipaddr.subnetMatch(this, this.SpecialRanges);
  246. };
  247. IPv6.prototype.isIPv4MappedAddress = function() {
  248. return this.range() === 'ipv4Mapped';
  249. };
  250. IPv6.prototype.toIPv4Address = function() {
  251. var high, low, _ref;
  252. if (!this.isIPv4MappedAddress()) {
  253. throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
  254. }
  255. _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1];
  256. return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
  257. };
  258. return IPv6;
  259. })();
  260. ipv6Part = "(?:[0-9a-f]+::?)+";
  261. ipv6Regexes = {
  262. "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'),
  263. transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i')
  264. };
  265. expandIPv6 = function(string, parts) {
  266. var colonCount, lastColon, part, replacement, replacementCount;
  267. if (string.indexOf('::') !== string.lastIndexOf('::')) {
  268. return null;
  269. }
  270. colonCount = 0;
  271. lastColon = -1;
  272. while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
  273. colonCount++;
  274. }
  275. if (string[0] === ':') {
  276. colonCount--;
  277. }
  278. if (string[string.length - 1] === ':') {
  279. colonCount--;
  280. }
  281. replacementCount = parts - colonCount;
  282. replacement = ':';
  283. while (replacementCount--) {
  284. replacement += '0:';
  285. }
  286. string = string.replace('::', replacement);
  287. if (string[0] === ':') {
  288. string = string.slice(1);
  289. }
  290. if (string[string.length - 1] === ':') {
  291. string = string.slice(0, -1);
  292. }
  293. return (function() {
  294. var _i, _len, _ref, _results;
  295. _ref = string.split(":");
  296. _results = [];
  297. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  298. part = _ref[_i];
  299. _results.push(parseInt(part, 16));
  300. }
  301. return _results;
  302. })();
  303. };
  304. ipaddr.IPv6.parser = function(string) {
  305. var match, parts;
  306. if (string.match(ipv6Regexes['native'])) {
  307. return expandIPv6(string, 8);
  308. } else if (match = string.match(ipv6Regexes['transitional'])) {
  309. parts = expandIPv6(match[1].slice(0, -1), 6);
  310. if (parts) {
  311. parts.push(parseInt(match[2]) << 8 | parseInt(match[3]));
  312. parts.push(parseInt(match[4]) << 8 | parseInt(match[5]));
  313. return parts;
  314. }
  315. }
  316. return null;
  317. };
  318. ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
  319. return this.parser(string) !== null;
  320. };
  321. ipaddr.IPv4.isValid = ipaddr.IPv6.isValid = function(string) {
  322. var e;
  323. try {
  324. new this(this.parser(string));
  325. return true;
  326. } catch (_error) {
  327. e = _error;
  328. return false;
  329. }
  330. };
  331. ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) {
  332. var parts;
  333. parts = this.parser(string);
  334. if (parts === null) {
  335. throw new Error("ipaddr: string is not formatted like ip address");
  336. }
  337. return new this(parts);
  338. };
  339. ipaddr.isValid = function(string) {
  340. return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
  341. };
  342. ipaddr.parse = function(string) {
  343. if (ipaddr.IPv6.isIPv6(string)) {
  344. return ipaddr.IPv6.parse(string);
  345. } else if (ipaddr.IPv4.isIPv4(string)) {
  346. return ipaddr.IPv4.parse(string);
  347. } else {
  348. throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
  349. }
  350. };
  351. ipaddr.process = function(string) {
  352. var addr;
  353. addr = this.parse(string);
  354. if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
  355. return addr.toIPv4Address();
  356. } else {
  357. return addr;
  358. }
  359. };
  360. }).call(this);