File size: 2,703 Bytes
f83effb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
 * 从多个外部服务获取服务器IP地址
 */
async function getServerIP(): Promise<string> {
  // 尝试多个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<string, any>;
        // 不同服务返回格式不同,需要适配
        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<Response> => {
  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' }
      }
    );
  }
}