使用Worker获取ip

你知唔知我系靓仔

使用Worker获取ip

最近爬代理的时候产生的需求,但是需要注意

在 Free 计划中,您每天可发送的 Worker 请求总数限制为 100,000 个。超过此限制后,发送到您的路由的请求将失败。

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  // 从请求头中获取客户端 IP 地址
  const ip = getClientIP(request);

  // 构建响应内容
  const responseText = `${ip}`;

  // 返回响应
  return new Response(responseText, {
    headers: { 'Content-Type': 'text/plain' },
  });
}

function getClientIP(request) {
  // 优先尝试获取 X-Forwarded-For 头
  const xForwardedFor = request.headers.get('X-Forwarded-For');
  if (xForwardedFor) {
    // X-Forwarded-For 可能包含多个 IP 地址,找到第一个有效的 IPv4 地址
    const ipv4Matches = xForwardedFor.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g);
    if (ipv4Matches && ipv4Matches.length > 0) {
      return ipv4Matches[0];
    }
    // 如果没有 IPv4 地址,则返回第一个 IP 地址
    return xForwardedFor.split(',')[0].trim();
  }

  // 如果 X-Forwarded-For 不存在,则使用 CF-Connecting-IP 头
  const cfConnectingIP = request.headers.get('CF-Connecting-IP');
  if (cfConnectingIP) {
    return cfConnectingIP;
  }

  // 如果以上头信息都不存在,返回请求的远程地址
  return request.headers.get('CF-Connecting-IP');
}