import express from 'express'; import ping from 'ping'; import 'dotenv/config'; const app = express(); const PORT = process.env.PORT; async function startPing(ips, res) { try { const pingResults = await Promise.all( ips.map(async (ip) => { try { const result = await ping.promise.probe(ip); if (result.alive == 1){ return { status: 200, time: new Date().toISOString(), result: [ { target: ip, alive: result.alive ? 1 : 0, "time ms": result.time + ' ms', output: result.output, } ] }; } else { return { status: 503, time: new Date().toISOString(), result: [ { target: ip, alive: result.alive ? 1 : 0, "time ms": result.time + ' ms', "status": "error", "message": "Network Unreachable", output: result.output } ] }; } } catch (error) { return { target: ip, error: error.message, }; } }) ); res.json(pingResults); } catch (error) { res.status(500).json({ error: 'Server error', details: error.message }); } } // Endpoint to check ping status app.get('/ping', async (req, res) => { try { const IPs = process.env.TARGET_IPS ? process.env.TARGET_IPS.split(',').map(ip => ip.trim()) : []; if (IPs.length === 0) { return res.status(400).json({ error: 'No target IPs configured in .env' }); } startPing(IPs, res); } catch (error) { res.status(500).json({ error: 'Failed to ping', details: error.message }); } }); // Start server app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });