NodeJS TCP ping example (Typescript)
The following Typescript example allows you to “ping” an IP address or host name not using ICMP but using TCP connection to a given port. If the TCP connection is accepted, the ping is resolved as true
. If no connection can be established, it is returned as false
. In any case, no data is exchanged and the connection is closed immediately after establishing it.
import { Socket } from "net";
/**
* Basic TCP ping that returns true if the connection is successful, false if it fails
* The socket is closed after the connection attempt, no data is exchanged.
*/
export function TCPConnectPing(ipAddress, timeout=5000, port=80): Promise<boolean> {
return new Promise((resolve) => {
const socket = new Socket();
let connected = false;
// Set a timeout for the connection attempt
const timer = setTimeout(() => {
if (!connected) {
socket.destroy();
resolve(false); // Connection timed out
}
}, timeout);
socket.connect(port, ipAddress, () => {
clearTimeout(timer);
connected = true;
socket.destroy();
resolve(true); // Connection successful
});
socket.on('error', (error) => {
clearTimeout(timer);
if (!connected) {
resolve(false); // Connection failed due to error
}
});
});
}