How about comrades, a few days ago I was trying to ICMP ping to an IP from NodeJS. But as is the rule in the forum, I do not come with empty hands, I have come across some posts even on this website talking about how to do this, but none of them convinces me.
One of the immovable parameters of my project is to avoid the use of NPM / Node-GYP. Therefore the option of using raw-sockets is discarded (unless you can use C ++ code in NodeJS without using things external to node itself).
Also tried (and implemented) the option of using system commands, here you can see my valid implementation for Linux and Windows (I have not tried it on Mac but I am almost sure it works)
'use strict';
import { execSync } from "child_process";
class Ping {
#stdoutToMS (stdout) {
let res;
let a = stdout.split('=');
for (let i = 0; i < a.length; i++) {
res = a[i].split("ms");
}
return ~~res[0].split('/')[0].trim();
}
ping (host, timeout = 5000) {
let mstout = timeout / 1000;
let stdout;
try {
if (process.platform === "win32") {
stdout = execSync("ping -n 1 -l 1 -w " + timeout + ' ' + host);
} else {
stdout = execSync("ping -c 1 -s 16 -W " + mstout + ' ' + host);
}
} catch (err) {
return false;
}
return this.#stdoutToMS(stdout.toString());
}
};
export default Ping;
If anyone has any ideas on how to do this natively in node without using external software, I'd be very grateful if you would tell me.
It does not appear you can access a ping equivalent from nodejs without some external code.
Since ping uses the ICMP protocol to do what it does (and it has to use that protocol because it's trying to contact an endpoint that is listening for that) and there is no implementation of the ICMP protocol in nodejs, your only option would be to create your own implementation of the ICMP protocol entirely in nodejs code by getting access to a RAW OS socket and implementing the protocol yourself. I am not aware of any built-in ability to get a RAW socket in plain nodejs (no external software).
The only examples of ICMP implementation I could find in nodejs ALL use external code to create access to a raw socket. That seems to be a verification that there is no other way to do it.
There is a module here that exposes a raw socket, but it uses some native code to implement that. You can examine its implementation to see what it's doing.
There's also this library which exposes a RAW socket from libuv to be used within nodejs, but it also uses some of it's own native code.