from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
ip = request.remote_addr
return render_template('index.html', user_ip=ip)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
request.remote_addr 直接返回與服務器建立 TCP 連接的客戶端 IP。
<div class="container">
<h3>Your IP Address</h3>
<strong>{{ user_ip }}</strong>
</div>
當 Flask 部署在 Nginx、Cloudflare、AWS ALB 等反向代理後方時,remote_addr 只能拿到代理服務器的 IP,而非真實用戶 IP。
X-Forwarded-For(鏈式,第一個為真實 IP)CF-Connecting-IPX-Forwarded-Forfrom werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(
app.wsgi_app,
x_for=1, # 信任第 1 層 X-Forwarded-For
x_proto=1, # 信任 X-Forwarded-Proto
x_host=1, # 信任 X-Forwarded-Host
x_prefix=1 # 信任 X-Forwarded-Prefix
)
配置後 request.remote_addr 自動解析為真實客戶端 IP。
def get_real_ip():
if request.headers.get('CF-Connecting-IP'):
return request.headers['CF-Connecting-IP']
xff = request.headers.get('X-Forwarded-For', '')
return xff.split(',')[0].strip() if xff else request.remote_addr
x_for=1 表示只信任直接上游代理remote_addr 與解析後 IP,便於審計