Ping Continuously Like Ping in CMD Using Node.Js
Asked Answered
E

2

5

I want use node.js to ping host in local network. Here is my code :

var ping = require('ping');

var host2 = ['192.168.0.1', '192.168.1.2', '192.168.2.3'];

host2.forEach(function(host){
    ping.sys.probe(host, function(active){
        var info = active ? 'IP ' + host + ' = Active' : 'IP ' + host + ' = Non-Active';
        console.log(info);
    });
});

This code only run (ping) once. All I want is to ping continuously. Is this possible with node.js?

EDIT : When I run the code :

enter image description here

EDIT 2 : When using setInterval / setTimeout :

Code :

var ping = require('ping');

var host2 = ['192.168.0.1', '192.168.1.2', '192.168.2.3'];

host2.forEach(function(host){
    ping.sys.probe(host, function tes(active){
        var info = active ? 'IP ' + host + ' = Active' : 'IP ' + host + ' = Non-Active';
        console.log(info);
    });
    setInterval(tes, 2000);
});

Result :

enter image description here

Electrograph answered 26/5, 2017 at 4:20 Comment(3)
setInterval will do the trickYeah
@Jorg, I've tried it, but the result is like above (EDIT 2)Electrograph
I'd wrap it around the foreach instead, less intervals (you're setting up an interval for every host). or around the entire thing, depending on where you want your variables to liveYeah
M
5

Well the obvious answer is this:

var ping = require('ping');

var host2 = ['192.168.0.1', '192.168.1.2', '192.168.2.3'];

var frequency = 1000; //1 second

host2.forEach(function(host){
    setInterval(function() {
        ping.sys.probe(host, function(active){
            var info = active ? 'IP ' + host + ' = Active' : 'IP ' + host + ' = Non-Active';
            console.log(info);
        });
    }, frequency);
});

That will ping each host in the host2 array once every second.

Misesteem answered 26/5, 2017 at 4:24 Comment(1)
Thanks for your solution :-)Electrograph
M
2

Now you can use async await for the ping module, please find it below -

const ping = require( 'ping' ),
    host = 'www.google.com';


( async () => {

    try {
        const isAlive =  await ping.promise.probe(host, { timeout: 10 });
        const msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
        console.log(msg);
    } catch ( error ) {
        console.log(error, "asassas")
    }

} )()
Mabel answered 9/4, 2020 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.