/** * 从多个外部服务获取服务器IP地址 */ async function getServerIP(): Promise { // 尝试多个IP查询服务,按顺序尝试,直到成功获取IP const ipServices = [ 'https://api.ipify.org?format=json', 'https://api.ip.sb/ip', 'https://api4.my-ip.io/ip.json', 'https://ipinfo.io/json' ]; for (const service of ipServices) { try { const response = await fetch(service, { method: 'GET', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } }); if (!response.ok) { continue; // 尝试下一个服务 } const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { const data = await response.json() as Record; // 不同服务返回格式不同,需要适配 if (data.ip) return data.ip; if (data.query) return data.query; if (data.YourFuckingIPAddress) return data.YourFuckingIPAddress; if (data.address) return data.address; } else { // 纯文本响应 const ip = await response.text(); return ip.trim(); } } catch (error) { console.error(`从 ${service} 获取IP失败:`, error); // 继续尝试下一个服务 } } return 'Unknown'; // 所有服务都失败时返回 } export const onRequest = async (context: RouteContext): Promise => { const request = context.request; try { // 获取客户端IP(来自请求头) const clientIP = request.headers.get('CF-Connecting-IP') || request.headers.get('X-Forwarded-For') || request.headers.get('X-Real-IP') || 'Unknown'; // 获取服务器主机名 const hostname = request.headers.get('Host') || 'Unknown'; // 从外部服务获取服务器的公网IP const serverIP = await getServerIP(); return new Response( JSON.stringify({ success: true, data: { clientIP: clientIP, serverIP: serverIP, hostname: hostname, serverTime: new Date().toISOString() } }), { status: 200, headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error(`获取IP地址失败:`, error); return new Response( JSON.stringify({ success: false, error: 'Failed to get IP address' }), { status: 500, headers: { 'Content-Type': 'application/json' } } ); } }