ExtractIPAddresses.mjs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import { search } from "../lib/Extract";
  8. /**
  9. * Extract IP addresses operation
  10. */
  11. class ExtractIPAddresses extends Operation {
  12. /**
  13. * ExtractIPAddresses constructor
  14. */
  15. constructor() {
  16. super();
  17. this.name = "Extract IP addresses";
  18. this.module = "Regex";
  19. this.description = "Extracts all IPv4 and IPv6 addresses.<br><br>Warning: Given a string <code>710.65.0.456</code>, this will match <code>10.65.0.45</code> so always check the original input!";
  20. this.inputType = "string";
  21. this.outputType = "string";
  22. this.args = [
  23. {
  24. "name": "IPv4",
  25. "type": "boolean",
  26. "value": true
  27. },
  28. {
  29. "name": "IPv6",
  30. "type": "boolean",
  31. "value": false
  32. },
  33. {
  34. "name": "Remove local IPv4 addresses",
  35. "type": "boolean",
  36. "value": false
  37. },
  38. {
  39. "name": "Display total",
  40. "type": "boolean",
  41. "value": false
  42. }
  43. ];
  44. }
  45. /**
  46. * @param {string} input
  47. * @param {Object[]} args
  48. * @returns {string}
  49. */
  50. run(input, args) {
  51. const [includeIpv4, includeIpv6, removeLocal, displayTotal] = args,
  52. ipv4 = "(?:(?:\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d|\\d)(?:\\/\\d{1,2})?",
  53. ipv6 = "((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|(?![\\dA-F])))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})";
  54. let ips = "";
  55. if (includeIpv4 && includeIpv6) {
  56. ips = ipv4 + "|" + ipv6;
  57. } else if (includeIpv4) {
  58. ips = ipv4;
  59. } else if (includeIpv6) {
  60. ips = ipv6;
  61. }
  62. if (ips) {
  63. const regex = new RegExp(ips, "ig");
  64. if (removeLocal) {
  65. const ten = "10\\..+",
  66. oneninetwo = "192\\.168\\..+",
  67. oneseventwo = "172\\.(?:1[6-9]|2\\d|3[01])\\..+",
  68. onetwoseven = "127\\..+",
  69. removeRegex = new RegExp("^(?:" + ten + "|" + oneninetwo +
  70. "|" + oneseventwo + "|" + onetwoseven + ")");
  71. return search(input, regex, removeRegex, displayTotal);
  72. } else {
  73. return search(input, regex, null, displayTotal);
  74. }
  75. } else {
  76. return "";
  77. }
  78. }
  79. }
  80. export default ExtractIPAddresses;