|
|
|
|
|
|
|
async function getServerIP(): Promise<string> { |
|
|
|
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 { |
|
|
|
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'; |
|
|
|
|
|
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' } |
|
} |
|
); |
|
} |
|
} |
|
|