ip.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. 'use strict';
  2. var ip = exports;
  3. var Buffer = require('buffer').Buffer;
  4. var os = require('os');
  5. ip.toBuffer = function toBuffer(ip, buff, offset) {
  6. offset = ~~offset;
  7. var result;
  8. if (/^::ffff:(\d{1,3}\.){3,3}\d{1,3}$/.test(ip)) {
  9. ip = ip.replace(/^::ffff:/, '');
  10. }
  11. if (/^(\d{1,3}\.){3,3}\d{1,3}$/.test(ip)) {
  12. result = buff || new Buffer(offset + 4);
  13. ip.split(/\./g).map(function(byte) {
  14. result[offset++] = parseInt(byte, 10) & 0xff;
  15. });
  16. } else if (/^[a-f0-9:]+$/.test(ip)) {
  17. var s = ip.split(/::/g, 2);
  18. var head = (s[0] || '').split(/:/g, 8);
  19. var tail = (s[1] || '').split(/:/g, 8);
  20. if (tail.length === 0) {
  21. // xxxx::
  22. while (head.length < 8) head.push('0000');
  23. } else if (head.length === 0) {
  24. // ::xxxx
  25. while (tail.length < 8) tail.unshift('0000');
  26. } else {
  27. // xxxx::xxxx
  28. while (head.length + tail.length < 8) head.push('0000');
  29. }
  30. result = buff || new Buffer(offset + 16);
  31. head.concat(tail).map(function(word) {
  32. word = parseInt(word, 16);
  33. result[offset++] = (word >> 8) & 0xff;
  34. result[offset++] = word & 0xff;
  35. });
  36. } else {
  37. throw Error('Invalid ip address: ' + ip);
  38. }
  39. return result;
  40. };
  41. ip.toString = function toString(buff, offset, length) {
  42. offset = ~~offset;
  43. length = length || (buff.length - offset);
  44. var result = [];
  45. if (length === 4) {
  46. // IPv4
  47. for (var i = 0; i < length; i++) {
  48. result.push(buff[offset + i]);
  49. }
  50. result = result.join('.');
  51. } else if (length === 16) {
  52. // IPv6
  53. for (var i = 0; i < length; i += 2) {
  54. result.push(buff.readUInt16BE(offset + i).toString(16));
  55. }
  56. result = result.join(':');
  57. result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3');
  58. result = result.replace(/:{3,4}/, '::');
  59. }
  60. return result;
  61. };
  62. function _normalizeFamily(family) {
  63. return family ? family.toLowerCase() : 'ipv4';
  64. }
  65. ip.fromPrefixLen = function fromPrefixLen(prefixlen, family) {
  66. if (prefixlen > 32) {
  67. family = 'ipv6';
  68. } else {
  69. family = _normalizeFamily(family);
  70. }
  71. var len = 4;
  72. if (family === 'ipv6') {
  73. len = 16;
  74. }
  75. var buff = new Buffer(len);
  76. for (var i = 0, n = buff.length; i < n; ++i) {
  77. var bits = 8;
  78. if (prefixlen < 8) {
  79. bits = prefixlen;
  80. }
  81. prefixlen -= bits;
  82. buff[i] = ~(0xff >> bits);
  83. }
  84. return ip.toString(buff);
  85. };
  86. ip.mask = function mask(addr, mask) {
  87. addr = ip.toBuffer(addr);
  88. mask = ip.toBuffer(mask);
  89. var result = new Buffer(Math.max(addr.length, mask.length));
  90. // Same protocol - do bitwise and
  91. if (addr.length === mask.length) {
  92. for (var i = 0; i < addr.length; i++) {
  93. result[i] = addr[i] & mask[i];
  94. }
  95. } else if (mask.length === 4) {
  96. // IPv6 address and IPv4 mask
  97. // (Mask low bits)
  98. for (var i = 0; i < mask.length; i++) {
  99. result[i] = addr[addr.length - 4 + i] & mask[i];
  100. }
  101. } else {
  102. // IPv6 mask and IPv4 addr
  103. for (var i = 0; i < result.length - 6; i++) {
  104. result[i] = 0;
  105. }
  106. // ::ffff:ipv4
  107. result[10] = 0xff;
  108. result[11] = 0xff;
  109. for (var i = 0; i < addr.length; i++) {
  110. result[i + 12] = addr[i] & mask[i + 12];
  111. }
  112. }
  113. return ip.toString(result);
  114. };
  115. ip.cidr = function cidr(cidrString) {
  116. var cidrParts = cidrString.split('/');
  117. var addr = cidrParts[0];
  118. if (cidrParts.length !== 2)
  119. throw new Error('invalid CIDR subnet: ' + addr);
  120. var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10));
  121. return ip.mask(addr, mask);
  122. };
  123. ip.subnet = function subnet(addr, mask) {
  124. var networkAddress = ip.toLong(ip.mask(addr, mask));
  125. // Calculate the mask's length.
  126. var maskBuffer = ip.toBuffer(mask);
  127. var maskLength = 0;
  128. for (var i = 0; i < maskBuffer.length; i++) {
  129. if (maskBuffer[i] === 0xff) {
  130. maskLength += 8;
  131. } else {
  132. var octet = maskBuffer[i] & 0xff;
  133. while (octet) {
  134. octet = (octet << 1) & 0xff;
  135. maskLength++;
  136. }
  137. }
  138. }
  139. var numberOfAddresses = Math.pow(2, 32 - maskLength);
  140. return {
  141. networkAddress: ip.fromLong(networkAddress),
  142. firstAddress: numberOfAddresses <= 2 ?
  143. ip.fromLong(networkAddress) :
  144. ip.fromLong(networkAddress + 1),
  145. lastAddress: numberOfAddresses <= 2 ?
  146. ip.fromLong(networkAddress + numberOfAddresses - 1) :
  147. ip.fromLong(networkAddress + numberOfAddresses - 2),
  148. broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1),
  149. subnetMask: mask,
  150. subnetMaskLength: maskLength,
  151. numHosts: numberOfAddresses <= 2 ?
  152. numberOfAddresses : numberOfAddresses - 2,
  153. length: numberOfAddresses
  154. };
  155. };
  156. ip.cidrSubnet = function cidrSubnet(cidrString) {
  157. var cidrParts = cidrString.split('/');
  158. var addr = cidrParts[0];
  159. if (cidrParts.length !== 2)
  160. throw new Error('invalid CIDR subnet: ' + addr);
  161. var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10));
  162. return ip.subnet(addr, mask);
  163. };
  164. ip.not = function not(addr) {
  165. var buff = ip.toBuffer(addr);
  166. for (var i = 0; i < buff.length; i++) {
  167. buff[i] = 0xff ^ buff[i];
  168. }
  169. return ip.toString(buff);
  170. };
  171. ip.or = function or(a, b) {
  172. a = ip.toBuffer(a);
  173. b = ip.toBuffer(b);
  174. // same protocol
  175. if (a.length === b.length) {
  176. for (var i = 0; i < a.length; ++i) {
  177. a[i] |= b[i];
  178. }
  179. return ip.toString(a);
  180. // mixed protocols
  181. } else {
  182. var buff = a;
  183. var other = b;
  184. if (b.length > a.length) {
  185. buff = b;
  186. other = a;
  187. }
  188. var offset = buff.length - other.length;
  189. for (var i = offset; i < buff.length; ++i) {
  190. buff[i] |= other[i - offset];
  191. }
  192. return ip.toString(buff);
  193. }
  194. };
  195. ip.isEqual = function isEqual(a, b) {
  196. a = ip.toBuffer(a);
  197. b = ip.toBuffer(b);
  198. // Same protocol
  199. if (a.length === b.length) {
  200. for (var i = 0; i < a.length; i++) {
  201. if (a[i] !== b[i]) return false;
  202. }
  203. return true;
  204. }
  205. // Swap
  206. if (b.length === 4) {
  207. var t = b;
  208. b = a;
  209. a = t;
  210. }
  211. // a - IPv4, b - IPv6
  212. for (var i = 0; i < 10; i++) {
  213. if (b[i] !== 0) return false;
  214. }
  215. var word = b.readUInt16BE(10);
  216. if (word !== 0 && word !== 0xffff) return false;
  217. for (var i = 0; i < 4; i++) {
  218. if (a[i] !== b[i + 12]) return false;
  219. }
  220. return true;
  221. };
  222. ip.isPrivate = function isPrivate(addr) {
  223. return /^10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(addr) ||
  224. /^192\.168\.([0-9]{1,3})\.([0-9]{1,3})/.test(addr) ||
  225. /^172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})/.test(addr) ||
  226. /^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(addr) ||
  227. /^169\.254\.([0-9]{1,3})\.([0-9]{1,3})/.test(addr) ||
  228. /^fc00:/.test(addr) ||
  229. /^fe80:/.test(addr) ||
  230. /^::1$/.test(addr) ||
  231. /^::$/.test(addr);
  232. };
  233. ip.isPublic = function isPublic(addr) {
  234. return !ip.isPrivate(addr);
  235. };
  236. ip.isLoopback = function isLoopback(addr) {
  237. return /^127\.\d+\.\d+\.\d+$/.test(addr) ||
  238. /^fe80::1$/.test(addr) ||
  239. /^::1$/.test(addr) ||
  240. /^::$/.test(addr);
  241. };
  242. ip.loopback = function loopback(family) {
  243. //
  244. // Default to `ipv4`
  245. //
  246. family = _normalizeFamily(family);
  247. if (family !== 'ipv4' && family !== 'ipv6') {
  248. throw new Error('family must be ipv4 or ipv6');
  249. }
  250. return family === 'ipv4' ? '127.0.0.1' : 'fe80::1';
  251. };
  252. //
  253. // ### function address (name, family)
  254. // #### @name {string|'public'|'private'} **Optional** Name or security
  255. // of the network interface.
  256. // #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults
  257. // to ipv4).
  258. //
  259. // Returns the address for the network interface on the current system with
  260. // the specified `name`:
  261. // * String: First `family` address of the interface.
  262. // If not found see `undefined`.
  263. // * 'public': the first public ip address of family.
  264. // * 'private': the first private ip address of family.
  265. // * undefined: First address with `ipv4` or loopback addres `127.0.0.1`.
  266. //
  267. ip.address = function address(name, family) {
  268. var interfaces = os.networkInterfaces();
  269. var all;
  270. //
  271. // Default to `ipv4`
  272. //
  273. family = _normalizeFamily(family);
  274. //
  275. // If a specific network interface has been named,
  276. // return the address.
  277. //
  278. if (name && name !== 'private' && name !== 'public') {
  279. var res = interfaces[name].filter(function(details) {
  280. var itemFamily = details.family.toLowerCase();
  281. return itemFamily === family;
  282. });
  283. if (res.length === 0)
  284. return undefined;
  285. return res[0].address;
  286. }
  287. var all = Object.keys(interfaces).map(function (nic) {
  288. //
  289. // Note: name will only be `public` or `private`
  290. // when this is called.
  291. //
  292. var addresses = interfaces[nic].filter(function (details) {
  293. details.family = details.family.toLowerCase();
  294. if (details.family !== family || ip.isLoopback(details.address)) {
  295. return false;
  296. } else if (!name) {
  297. return true;
  298. }
  299. return name === 'public' ? !ip.isPrivate(details.address) :
  300. ip.isPrivate(details.address);
  301. });
  302. return addresses.length ? addresses[0].address : undefined;
  303. }).filter(Boolean);
  304. return !all.length ? ip.loopback(family) : all[0];
  305. };
  306. ip.toLong = function toInt(ip) {
  307. var ipl = 0;
  308. ip.split('.').forEach(function(octet) {
  309. ipl <<= 8;
  310. ipl += parseInt(octet);
  311. });
  312. return(ipl >>> 0);
  313. };
  314. ip.fromLong = function fromInt(ipl) {
  315. return ((ipl >>> 24) + '.' +
  316. (ipl >> 16 & 255) + '.' +
  317. (ipl >> 8 & 255) + '.' +
  318. (ipl & 255) );
  319. };