正確顯示 ip 結果 ( cloudflare )

This commit is contained in:
2025-10-07 17:57:17 +08:00
parent 0e517dc694
commit 707820697a
8 changed files with 935 additions and 46 deletions

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { getClientIp, isIpAllowed, getIpLocation, getDetailedIpInfo } from '@/lib/ip-utils'
import { getClientIp, isIpAllowed, getIpLocation, getDetailedIpInfo, isValidIp, isValidIPv6 } from '@/lib/ip-utils'
// 強制動態渲染
export const dynamic = 'force-dynamic'
@@ -10,6 +10,17 @@ export async function GET(request: NextRequest) {
const detailedInfo = getDetailedIpInfo(request);
let clientIp = detailedInfo.detectedIp;
// 根據你的環境,優先使用 cf-connecting-ip (支持IPv4和IPv6)
const cfConnectingIp = request.headers.get('cf-connecting-ip');
if (cfConnectingIp && cfConnectingIp.trim() !== '') {
const cleanCfIp = cfConnectingIp.trim();
// 检查是否是有效的IPv4或IPv6地址
if (isValidIp(cleanCfIp) || isValidIPv6(cleanCfIp)) {
clientIp = cleanCfIp;
console.log('使用 cf-connecting-ip:', clientIp, isValidIPv6(clientIp) ? '(IPv6)' : '(IPv4)');
}
}
// 確保返回IPv4格式的地址
function ensureIPv4Format(ip: string): string {
if (!ip) return '127.0.0.1';