边缘开发者平台
  • 边缘函数
    • 概述
    • 快速指引
    • 操作指引
      • 函数管理
      • Web调试
      • 触发配置
      • 环境变量
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • 示例函数
      • 示例概述
      • 301重定向
      • 获取客户端URL信息
      • 基于客户端地理位置的自定义
      • 获取客户端地理位置信息
      • 批量重定向
      • 返回 HTML 页面
      • 返回 JSON
      • Fetch 远程资源
      • 请求头鉴权
      • 修改响应头
      • AB 测试
      • 设置 Cookie
      • 基于请求区域重定向
      • Cache API 使用
      • 缓存 POST 请求
      • 流式响应
      • 合并资源流式响应
      • 防篡改校验
      • m3u8 改写与鉴权
      • 图片自适应缩放
      • 图片自适应 WebP
      • 自定义 Referer 限制规则
      • 远程鉴权
      • HMAC 数字签名
      • 自定义下载文件名
      • 获取客户端 IP
    • 最佳实践
      • 通过边缘函数实现自适应图片格式转换
当前内容仅提供英语版本,中文版我们将尽快补充,感谢您的理解。

获取客户端 IP

Since the front end cannot directly obtain the client IP address, it's often necessary to obtain the client IP address through the server side or third-party services in multiple business scenarios. The client IP address is obtained in this example through client IP header EO-Client-IP activated in the rule engine, and assembled into data in the form of JSON to respond to the clients, which succeeds in obtaining client IP address by the use of edge function.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

function handleRequest(request) {
// Obtain the client IP through the EO-Client-IP header
const ip = request.headers.get('EO-Client-IP') || '';
// Respond with JSON data
return new Response(JSON.stringify({ ip }), {
headers: { 'content-type': 'application/json' },
});
}

Sample Preview

Firstly, activate the client IP switch of the domain name that needs to trigger the edge function and set the header name as EO-Client-IP in the Rule Engine configuration.

Once the configuration is effective, enter a URL (such as https://example.com/ip) which matches the trigger rule of the edge function in the address bar of the browser on both the PC and mobile terminal to obtain the client's IP address:


Related References