ip.js 10 KB

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