Ping Continuously like Ping in CMD Using Node.Js
I want to use node.js to ping a host on a 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 runs once (ping). All I want is to ping constantly. Is this possible with node.js?
EDIT: When I run the code:
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:
+3
source to share
1 answer
Well, the obvious answer is:
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);
});
This will ping every node in the array host2
once per second.
+1
source to share