O seguinte exemplo Typescript permite que você “pingue” um endereço IP ou nome de host não usando ICMP mas usando conexão TCP para uma porta dada. Se a conexão TCP for aceita, o ping é resolvido como true. Se nenhuma conexão puder ser estabelecida, é retornado como false. Em qualquer caso, nenhum dado é trocado e a conexão é fechada imediatamente após estabelecê-la.
tcp_ping.ts
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
}
});
});
}If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow