ip.js 10.0 KB

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