本題摘自於我 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