Download Game! Currently 80 players and visitors. Last logged in:JanoQumniGrizztSahadev

Blitzer's Blog >> 72314

Back to blogs index
Posted: 13 Sep 2026 10:52 [ permalink ]
$
$ cat ./build/ASYNC_PING_MANAGER.js
const { exec } = require('child_process');
const loadServerList = require('./SERVER_LIST_LOADER');

const DEFAULT_TIMEOUT_MS = 5000;
const DEFAULT_CONCURRENCY = 10;

function pingHost(ip, timeoutMs) {
  return new Promise((resolve) => {
    const isWindows = process.platform === 'win32';
    const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
    const command = isWindows
      ? `ping -n 1 -w ${timeoutMs} ${ip}`
      : `ping -c 1 -W ${timeoutSeconds} ${ip}`;

    exec(command, { timeout: timeoutMs + 1000 }, (error, stdout, stderr) => {
      if (error) {
        resolve({ ip, alive: false, error: error.message, output: stdout ||
stderr || '' });
      } else {
        resolve({ ip, alive: true, output: stdout });
      }
    });
  });
}

async function runWithConcurrency(tasks, concurrency) {
  const results = new Array(tasks.length);
  let nextIndex = 0;

  async function worker() {
    while (true) {
      const currentIndex = nextIndex++;
      if (currentIndex >= tasks.length) {
        return;
      }
      results[currentIndex] = await tasks[currentIndex]();
    }
  }

  const workerCount = Math.max(1, Math.min(concurrency, tasks.length));
  const workers = [];
  for (let i = 0; i < workerCount; i++) {
    workers.push(worker());
  }
  await Promise.all(workers);
  return results;
}

async function pingAll(options = {}) {
  const timeoutMs = typeof options.timeoutMs === 'number' ? options.timeoutMs
: DEFAULT_TIMEOUT_MS;
  const concurrency = typeof options.concurrency === 'number' ?
options.concurrency : DEFAULT_CONCURRENCY;

  let servers;
  try {
    servers = loadServerList();
  } catch (err) {
    throw new Error(`Failed to load server list: ${err.message}`);
  }

  if (!Array.isArray(servers)) {
    throw new Error('Server list must be an array of IP addresses');
  }

  const ips = servers
    .map((entry) => (typeof entry === 'string' ? entry : entry && entry.ip))
    .filter((ip) => typeof ip === 'string' && ip.length > 0);

  const tasks = ips.map((ip) => () => pingHost(ip, timeoutMs));
  const results = await runWithConcurrency(tasks, concurrency);

  const alive = results.filter((r) => r.alive);
  const dead = results.filter((r) => !r.alive);

  return {
    total: results.length,
    aliveCount: alive.length,
    deadCount: dead.length,
    results,
    alive,
    dead,
  };
}

module.exports = {
  pingHost,
  pingAll,
  DEFAULT_TIMEOUT_MS,
  DEFAULT_CONCURRENCY,
$