服务器端如何得到客户端 IP 地址

本题摘自于我 github 上的面试每日一题:github.com/shfshanyue/…前端

这是一道腾讯的面试题git

若是有 x-forwarded-for 的请求头,则取其中的第一个 IP,不然取创建链接 socket 的 remoteAddr。github

x-forwarded-for 基本已成为了基于 proxy 的标准HTTP头,格式以下,可见第一个 IP 表明其真实的 IP,能够参考 MDN X-Forwarded-For面试

X-Forwarded-For: 203.0.113.195, 70.41.3.18, 150.172.238.178
X-Forwarded-For: <client>, <proxy1>, <proxy2>
复制代码

如下是 koa 获取 IP 的方法微信

get ips() {
    const proxy = this.app.proxy;
    const val = this.get(this.app.proxyIpHeader);
    let ips = proxy && val
      ? val.split(/\s*,\s*/)
      : [];
    if (this.app.maxIpsCount > 0) {
      ips = ips.slice(-this.app.maxIpsCount);
    }
    return ips;
  },

  get ip() {
    if (!this[IP]) {
      this[IP] = this.ips[0] || this.socket.remoteAddress || '';
    }
    return this[IP];
  },
复制代码

参见源码: github.com/koajs/koa/b…app

关注我

扫码添加个人微信,备注进群,加入高级前端进阶群koa

加我微信拉你进入面试交流群
加我微信拉你进入面试交流群
相关文章
相关标签/搜索