NodeJS TCP ping příklad (Typescript)

Následující Typescript příklad vám umožňuje “ping” IP adresu nebo host name nepoužitím ICMP ale použitím TCP connection k given port. Pokud TCP connection je accepted, ping je resolved jako true. Pokud no connection může být established, je returned jako false. V každém případě, no data je exchanged a connection je closed immediately po establishing.

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
        }
      });
    });
  }

Podívejte se na podobné články podle kategorie: Sítě NodeJS