<?php
header('Content-Type: application/json');

// 允许跨域访问
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");

function tcPing($ip, $port, $timeout = 3) {
    $start = microtime(true);
    $socket = @fsockopen($ip, $port, $errno, $errstr, $timeout);
    
    if (!$socket) {
        return [
            'status'  => 'failed',
            'error'   => "$errstr (Code: $errno)",
            'ip'      => $ip,
            'port'    => $port,
            'latency' => null
        ];
    }
    
    fclose($socket);
    return round((microtime(true) - $start) * 100, 2);
}

// 处理请求参数
$ip = $_REQUEST['ip'] ?? '';
$port = intval($_REQUEST['port'] ?? 80);
$timeout = intval($_REQUEST['timeout'] ?? 3);

if (empty($ip)) {
    http_response_code(400);
    die(json_encode(['error' => 'IP参数不能为空']));
}

// 执行检测
$latency = tcPing($ip, $port, $timeout);

// 返回标准化响应
echo json_encode([
    'data' => [
        'ip' => $ip,
        'port' => $port,
        'latency_ms' => is_numeric($latency) ? $latency : null,
        'status' => is_numeric($latency) ? 'success' : '超时',
        'timestamp' => date('Y-m-d H:i:s')
    ],
    'code' => is_numeric($latency) ? 200 : 500
], JSON_PRETTY_PRINT);
?>