From 2842b327770dd479c46d6e713fc4cfc20564dfef Mon Sep 17 00:00:00 2001 From: scdhh Date: Thu, 8 Aug 2024 20:22:19 +0800 Subject: [PATCH] Feat: Get client real ip from header --- filters/LimitIp.cc | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/filters/LimitIp.cc b/filters/LimitIp.cc index f61c5f3..be6a157 100644 --- a/filters/LimitIp.cc +++ b/filters/LimitIp.cc @@ -14,13 +14,27 @@ using namespace techmino::plugins; using namespace techmino::structures; using namespace techmino::types; +static string getClientIp( + const HttpRequestPtr& req +) { + auto& xForwardedFor = req->getHeader("X-Forwarded-For"); + if (!xForwardedFor.empty()) { + return xForwardedFor.substr(0, xForwardedFor.find(',')); + } + auto& xRealIp = req->getHeader("X-Real-IP"); + if (!xRealIp.empty()) { + return xRealIp; + } + return req->getPeerAddr().toIp(); +} + void LimitIp::doFilter( const HttpRequestPtr &req, FilterCallback &&failedCb, FilterChainCallback &&nextCb ) { try { - if (!app().getPlugin()->ipLimit(req->getPeerAddr().toIp())) { + if (!app().getPlugin()->ipLimit(getClientIp(req))) { ResponseJson(k429TooManyRequests, ResultCode::TooFrequent) .setMessage(i18n("tooFrequent")) .to(failedCb);