Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. (async () => {
  2.  
  3. const net = require('net');
  4. const dns = require('dns');
  5. const fs = require('fs');
  6.  
  7. const [,,host,portmin,portmax] = process.argv;
  8.  
  9. let a = Date.now();
  10. const ipv4 = await new Promise((ok,fail) =>
  11. dns.lookup(host, { family: 4, verbatim: true }, (err, address, family) =>
  12. err ? fail(err) : ok(address)));
  13. let elapsed = Date.now() - a;
  14.  
  15. if (ipv4 !== host) {
  16. console.log(`Resolved hostname ${host} to ${ipv4} in ${elapsed} ms.`);
  17. }
  18.  
  19. const TIMEOUT = 3*1000;
  20.  
  21. function probe(host, port, cb) {
  22. let connect, timeout, hangup, error, data, end, emitted;
  23.  
  24. const client = net.createConnection({
  25. port,
  26. host: ipv4,
  27. timeout: TIMEOUT,
  28. family: 4,
  29. lookup: () => {},
  30. }, () => {
  31. connect = true;
  32. });
  33. client.setNoDelay(true);
  34. client.setKeepAlive(false);
  35. client.setEncoding('utf8');
  36.  
  37. const done = () => {
  38. if (emitted) return;
  39. emitted = true;
  40. clearTimeout(timer);
  41. cb({ port, connect, timeout, hangup, error, data, end });
  42. };
  43.  
  44. const timer = setTimeout(()=>{
  45. hangup = true;
  46. client.end();
  47. done();
  48. }, TIMEOUT+1000);
  49.  
  50. client.on('timeout', () => { timeout = true; done(); });
  51. client.on('error', (e) => { error = e; });
  52. client.on('data', (d) => { null == data ? data = d : data += d; });
  53. client.on('end', () => { end=true; done(); });
  54. // other events: close, connect, drain, lookup, ready
  55. }
  56.  
  57. const CONCURRENCY = 100;
  58.  
  59. let running = 0;
  60. let port = portmin;
  61. const ports = [];
  62. for (let i=portmin; i<=portmax; i++) ports.push(i);
  63. ports.sort(()=>.5-Math.random());
  64.  
  65. const next = () => {
  66. running--;
  67. if (ports.length > 0) {
  68. const port = ports.pop();
  69. probe(host, port, (outcome) => {
  70. render(outcome);
  71. process.nextTick(next);
  72. });
  73. running++;
  74. }
  75. else if (running < 1) {
  76. console.log('\n\ndone.');
  77. process.exit(0);
  78. }
  79. };
  80.  
  81. for (let i=0; i<CONCURRENCY; i++) {
  82. running++;
  83. next();
  84. }
  85.  
  86. let lastRenderedDot = false;
  87. const render = (outcome) => {
  88. let out;
  89. if (outcome.timeout) {
  90. out = (lastRenderedDot ? '' : '\n') + '.';
  91. lastRenderedDot = true;
  92. }
  93. else {
  94. out = '\n'+JSON.stringify(outcome);
  95. lastRenderedDot = false;
  96. }
  97. fs.appendFileSync('./out.log', out);
  98. process.stdout.write(out);
  99. };
  100.  
  101. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement