Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Last active January 25, 2022 09:01
Show Gist options
  • Save benjamingr/ead0583c9979007e42ed3b99650636fa to your computer and use it in GitHub Desktop.
Save benjamingr/ead0583c9979007e42ed3b99650636fa to your computer and use it in GitHub Desktop.

Revisions

  1. benjamingr revised this gist Jan 25, 2022. 1 changed file with 2 additions and 5 deletions.
    7 changes: 2 additions & 5 deletions security-guild-meetup-exercise-port-scanner.mjs
    Original file line number Diff line number Diff line change
    @@ -21,11 +21,8 @@ const from = process.env.FROM_PORT ?? 2000;
    const to = process.env.TO_PORT ?? 3000;
    const concurrency = process.env.PARALLELISM ?? 100;
    const status = await Readable.from(range(from, to)).map(async x => {
    const hasPortOpen = await tryToConnectToPort(x, 'localhost');
    const hasPortOpen = await tryToConnectToPort(x, process.env.HOST ?? '20.203.26.203');
    return { port: x, open: hasPortOpen };
    }, { concurrency }).filter(x => x.open).toArray();

    console.log("Port status", status);

    // Example usage: FROM_PORT=2108 TO_PORT=2111 ./out/Release/node ~/Desktop/scanner.mjs
    // Runs on Node.js nightly or master https://nodejs.org/download/nightly/ (requires v17.5 + for Readable stream filter)
    console.log("Port status", status)
  2. benjamingr created this gist Jan 25, 2022.
    31 changes: 31 additions & 0 deletions security-guild-meetup-exercise-port-scanner.mjs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    import { connect } from 'net';
    import { once } from 'events';
    import { Readable } from 'stream';

    function* range(from, to) {
    for(let i = from; i < to; i++) yield i;
    }
    async function tryToConnectToPort(port, host) {
    const socket = connect(port, host);
    try {
    await once(socket, 'connect');
    } catch (e) {
    return false;
    } finally {
    socket.end();
    }
    return true;
    }

    const from = process.env.FROM_PORT ?? 2000;
    const to = process.env.TO_PORT ?? 3000;
    const concurrency = process.env.PARALLELISM ?? 100;
    const status = await Readable.from(range(from, to)).map(async x => {
    const hasPortOpen = await tryToConnectToPort(x, 'localhost');
    return { port: x, open: hasPortOpen };
    }, { concurrency }).filter(x => x.open).toArray();

    console.log("Port status", status);

    // Example usage: FROM_PORT=2108 TO_PORT=2111 ./out/Release/node ~/Desktop/scanner.mjs
    // Runs on Node.js nightly or master https://nodejs.org/download/nightly/ (requires v17.5 + for Readable stream filter)