ip.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. // check loopback addresses first
  256. if (ip.isLoopback(addr)) {
  257. return true;
  258. }
  259. // ensure the ipv4 address is valid
  260. if (!ip.isV6Format(addr)) {
  261. const ipl = ip.normalizeToLong(addr);
  262. if (ipl < 0) {
  263. throw new Error('invalid ipv4 address');
  264. }
  265. // normalize the address for the private range checks that follow
  266. addr = ip.fromLong(ipl);
  267. }
  268. // check private ranges
  269. return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr)
  270. || /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr)
  271. || /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i
  272. .test(addr)
  273. || /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr)
  274. || /^f[cd][0-9a-f]{2}:/i.test(addr)
  275. || /^fe80:/i.test(addr)
  276. || /^::1$/.test(addr)
  277. || /^::$/.test(addr);
  278. };
  279. ip.isPublic = function (addr) {
  280. return !ip.isPrivate(addr);
  281. };
  282. ip.isLoopback = function (addr) {
  283. // If addr is an IPv4 address in long integer form (no dots and no colons), convert it
  284. if (!/\./.test(addr) && !/:/.test(addr)) {
  285. addr = ip.fromLong(Number(addr));
  286. }
  287. return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/
  288. .test(addr)
  289. || /^0177\./.test(addr)
  290. || /^0x7f\./i.test(addr)
  291. || /^fe80::1$/i.test(addr)
  292. || /^::1$/.test(addr)
  293. || /^::$/.test(addr);
  294. };
  295. ip.loopback = function (family) {
  296. //
  297. // Default to `ipv4`
  298. //
  299. family = _normalizeFamily(family);
  300. if (family !== 'ipv4' && family !== 'ipv6') {
  301. throw new Error('family must be ipv4 or ipv6');
  302. }
  303. return family === 'ipv4' ? '127.0.0.1' : 'fe80::1';
  304. };
  305. //
  306. // ### function address (name, family)
  307. // #### @name {string|'public'|'private'} **Optional** Name or security
  308. // of the network interface.
  309. // #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults
  310. // to ipv4).
  311. //
  312. // Returns the address for the network interface on the current system with
  313. // the specified `name`:
  314. // * String: First `family` address of the interface.
  315. // If not found see `undefined`.
  316. // * 'public': the first public ip address of family.
  317. // * 'private': the first private ip address of family.
  318. // * undefined: First address with `ipv4` or loopback address `127.0.0.1`.
  319. //
  320. ip.address = function (name, family) {
  321. const interfaces = os.networkInterfaces();
  322. //
  323. // Default to `ipv4`
  324. //
  325. family = _normalizeFamily(family);
  326. //
  327. // If a specific network interface has been named,
  328. // return the address.
  329. //
  330. if (name && name !== 'private' && name !== 'public') {
  331. const res = interfaces[name].filter((details) => {
  332. const itemFamily = _normalizeFamily(details.family);
  333. return itemFamily === family;
  334. });
  335. if (res.length === 0) {
  336. return undefined;
  337. }
  338. return res[0].address;
  339. }
  340. const all = Object.keys(interfaces).map((nic) => {
  341. //
  342. // Note: name will only be `public` or `private`
  343. // when this is called.
  344. //
  345. const addresses = interfaces[nic].filter((details) => {
  346. details.family = _normalizeFamily(details.family);
  347. if (details.family !== family || ip.isLoopback(details.address)) {
  348. return false;
  349. } if (!name) {
  350. return true;
  351. }
  352. return name === 'public' ? ip.isPrivate(details.address)
  353. : ip.isPublic(details.address);
  354. });
  355. return addresses.length ? addresses[0].address : undefined;
  356. }).filter(Boolean);
  357. return !all.length ? ip.loopback(family) : all[0];
  358. };
  359. ip.toLong = function (ip) {
  360. let ipl = 0;
  361. ip.split('.').forEach((octet) => {
  362. ipl <<= 8;
  363. ipl += parseInt(octet);
  364. });
  365. return (ipl >>> 0);
  366. };
  367. ip.fromLong = function (ipl) {
  368. return (`${ipl >>> 24}.${
  369. ipl >> 16 & 255}.${
  370. ipl >> 8 & 255}.${
  371. ipl & 255}`);
  372. };
  373. ip.normalizeToLong = function (addr) {
  374. const parts = addr.split('.').map(part => {
  375. // Handle hexadecimal format
  376. if (part.startsWith('0x') || part.startsWith('0X')) {
  377. return parseInt(part, 16);
  378. }
  379. // Handle octal format (strictly digits 0-7 after a leading zero)
  380. else if (part.startsWith('0') && part !== '0' && /^[0-7]+$/.test(part)) {
  381. return parseInt(part, 8);
  382. }
  383. // Handle decimal format, reject invalid leading zeros
  384. else if (/^[1-9]\d*$/.test(part) || part === '0') {
  385. return parseInt(part, 10);
  386. }
  387. // Return NaN for invalid formats to indicate parsing failure
  388. else {
  389. return NaN;
  390. }
  391. });
  392. if (parts.some(isNaN)) return -1; // Indicate error with -1
  393. let val = 0;
  394. const n = parts.length;
  395. switch (n) {
  396. case 1:
  397. val = parts[0];
  398. break;
  399. case 2:
  400. if (parts[0] > 0xff || parts[1] > 0xffffff) return -1;
  401. val = (parts[0] << 24) | (parts[1] & 0xffffff);
  402. break;
  403. case 3:
  404. if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xffff) return -1;
  405. val = (parts[0] << 24) | (parts[1] << 16) | (parts[2] & 0xffff);
  406. break;
  407. case 4:
  408. if (parts.some(part => part > 0xff)) return -1;
  409. val = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3];
  410. break;
  411. default:
  412. return -1; // Error case
  413. }
  414. return val >>> 0;
  415. };