ping static method

Future<double> ping(
  1. String host
)

Ping工具函数 host 要ping的主机地址(域名或IP) @return 返回ping的延迟时间,单位毫秒(ms) @example

double latency = await Tools.ping('www.google.com');
print('延迟: ${latency}ms');

Implementation

static Future<double> ping(String host) async {
  try {
    final stopwatch = Stopwatch()..start();

    // 创建Socket连接
    final socket = await Socket.connect(
      host,
      80, // 使用HTTP端口
      timeout: const Duration(seconds: 5), // 5秒超时
    );

    stopwatch.stop();
    socket.destroy();

    // 返回延迟时间(毫秒)
    return stopwatch.elapsedMicroseconds / 1000.0;
  } catch (e) {
    // 如果连接失败,返回-1表示超时或无法连接
    return -1.0;
  }
}