【问题标题】:Get client IP in Koa.js在 Koa.js 中获取客户端 IP
【发布时间】:2016-10-07 21:47:19
【问题描述】:

我有一个带有这样的处理程序的 Koa 应用程序:

router.get('/admin.html', function *(next) {
    const clientIP = "?";
    this.body = `Hello World ${clientIp}`;
});

我需要获取客户端的 IP 地址以形成响应。如何分配 clientIp 以便它引用请求的 IP 地址。

【问题讨论】:

    标签: javascript node.js koa


    【解决方案1】:

    我遇到了同样的问题,但通过使用 NPM 上的这个模块解决了它 request-ip

    在koa中可以简单的使用userIp = requestIp.getClientIp(ctx.request)

    用户ip由以下顺序决定:

    X-Client-IP
    X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
    CF-Connecting-IP (Cloudflare)
    Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
    True-Client-Ip (Akamai and Cloudflare)
    X-Real-IP (Nginx proxy/FastCGI)
    X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
    X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
    req.connection.remoteAddress
    req.socket.remoteAddress
    req.connection.socket.remoteAddress
    req.info.remoteAddress
    

    如果找不到IP地址,则返回null。

    【讨论】:

      【解决方案2】:

      如果你添加 app.proxy=true 您仍然可以使用request.ip,而不必担心 IP 标头。

      【讨论】:

        【解决方案3】:

        Koa 1:

        假设您没有反向代理,您可以像这样使用this.request.ip

        router.get('/admin.html', function *(next) {
            const clientIP = this.request.ip;
            this.body = `Hello World ${clientIP}`;
        });
        

        request 文档中记录了此功能。您始终可以以this.request 的形式访问上述request 对象。

        如果您有反向代理,您将始终获得反向代理的 IP 地址。在这种情况下,它更棘手:在反向代理配置中,您需要添加一个特殊的标头,例如X-Orig-IP 使用原始客户端 IP。

        然后,你可以在 koa 中使用:

        const clientIp = this.request.headers["X-Orig-IP"];
        

        Koa 2:

        方法很相似,只是语法略有不同:

        router.get('/', async (ctx, next) => {
            const clientIP = ctx.request.ip;
            ctx.body = `Hello World ${clientIP}`;
        })
        

        【讨论】:

        • @Qasim 我会添加一个示例。
        • 我得到了一个 ipv6 ip,是否有可能得到 ipv4?
        • @chovy 在这种情况下,您的客户端使用 IPv6 连接到服务器。在服务器上禁用 IPv6 以避免这种情况。
        猜你喜欢
        • 2015-06-06
        • 2020-11-10
        • 2020-12-08
        • 1970-01-01
        • 2017-08-11
        • 1970-01-01
        • 1970-01-01
        • 2012-09-25
        • 2013-10-16
        相关资源
        最近更新 更多