使用这个库:request-ip
它按照如下顺序获取请求的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 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)
- appengine-user-ip (Google App Engine)
- req.connection.remoteAddress
- req.socket.remoteAddress
- req.connection.socket.remoteAddress
- req.info.remoteAddress
- Cf-Pseudo-IPv4 (Cloudflare fallback)
- request.raw (Fastify)
如果最后都找不到,则返回null。