zhemima/msmail
0
1/**2 * 从多个外部服务获取服务器IP地址3 */4async function getServerIP(): Promise<string> {5 // 尝试多个IP查询服务,按顺序尝试,直到成功获取IP6 const ipServices = [7 'https://api.ipify.org?format=json',8 'https://api.ip.sb/ip',9 'https://api4.my-ip.io/ip.json',10 'https://ipinfo.io/json'11 ];12 13 for (const service of ipServices) {14 try {15 const response = await fetch(service, {16 method: 'GET',17 headers: {18 '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'19 }20 });21 22 if (!response.ok) {23 continue; // 尝试下一个服务24 }25 26 const contentType = response.headers.get('content-type');27 28 if (contentType && contentType.includes('application/json')) {29 const data = await response.json() as Record<string, any>;30 // 不同服务返回格式不同,需要适配31 if (data.ip) return data.ip;32 if (data.query) return data.query;33 if (data.YourFuckingIPAddress) return data.YourFuckingIPAddress;34 if (data.address) return data.address;35 } else {36 // 纯文本响应37 const ip = await response.text();38 return ip.trim();39 }40 } catch (error) {41 console.error(`从 ${service} 获取IP失败:`, error);42 // 继续尝试下一个服务43 }44 }45 46 return 'Unknown'; // 所有服务都失败时返回47}48 49export const onRequest = async (context: RouteContext): Promise<Response> => {50 const request = context.request;51 52 try {53 // 获取客户端IP(来自请求头)54 const clientIP = request.headers.get('CF-Connecting-IP') ||55 request.headers.get('X-Forwarded-For') ||56 request.headers.get('X-Real-IP') ||57 'Unknown';58 59 // 获取服务器主机名60 const hostname = request.headers.get('Host') || 'Unknown';61 62 // 从外部服务获取服务器的公网IP63 const serverIP = await getServerIP();64 65 return new Response(66 JSON.stringify({67 success: true,68 data: {69 clientIP: clientIP,70 serverIP: serverIP,71 hostname: hostname,72 serverTime: new Date().toISOString()73 }74 }),75 {76 status: 200,77 headers: { 'Content-Type': 'application/json' }78 }79 );80 } catch (error) {81 console.error(`获取IP地址失败:`, error);82 83 return new Response(84 JSON.stringify({85 success: false,86 error: 'Failed to get IP address'87 }),88 {89 status: 500,90 headers: { 'Content-Type': 'application/json' }91 }92 );93 }94}95 