Пример NodeJS TCP ping (Typescript)

Следующий пример на Typescript позволяет вам “пропинговать” IP-адрес или имя хоста не используя ICMP, а используя TCP-подключение к заданному порту. Если TCP-подключение принято, пинг разрешается как true. Если подключение не может быть установлено, возвращается false. В любом случае, данные не обмениваются, и подключение закрывается сразу после его установления.

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

Check out similar posts by category: Сети NodeJS