NodeJS TCP ping 示例(Typescript)

以下 Typescript 示例允许你"ping"IP 地址或主机名,不使用 ICMP 而是使用 TCP 连接到给定端口。如果 TCP 连接被接受,ping 解析为 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: Networking, NodeJS