我不完全明白我应该如何获得一个远程用户IP地址。

假设我有一个简单的请求路由,如:

app.get(/, function (req, res){
   var forwardedIpsStr = req.header('x-forwarded-for');
   var IP = '';

   if (forwardedIpsStr) {
      IP = forwardedIps = forwardedIpsStr.split(',')[0];  
   }
});

上面的方法是否正确,以获得真实的用户IP地址或有更好的方法? 那么代理呢?


当前回答

根据快递背后的代理,要求。如果正确配置了信任代理,则IP已考虑反向代理。因此,它比req.connection.remoteAddress要好,因为req.connection.remoteAddress是从网络层获取的,不需要代理。

其他回答

如果你很好使用第三方库。可以检查request-ip。

你可以用is by

import requestIp from 'request-ip';

app.use(requestIp.mw())

app.use((req, res) => {
  const ip = req.clientIp;
});

源代码很长,所以我就不复制了,你可以在https://github.com/pbojinov/request-ip/blob/master/src/index.js上查看

基本上,

It looks for specific headers in the request and falls back to some defaults if they do not exist. The user ip is determined by the following order: 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 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) req.connection.remoteAddress req.socket.remoteAddress req.connection.socket.remoteAddress req.info.remoteAddress If an IP address cannot be found, it will return null.

公开:我和图书馆没有关系。

我知道这个问题已经有了答案,但下面是我如何让我的问题起作用的。

let ip = req.connection.remoteAddress.split(`:`).pop();

var ip = req.connection.remoteAddress;

IP = IP .split(':')[3];

这只是这个答案的附加信息。

如果你正在使用nginx,你需要添加proxy_set_header X-Real-IP $remote_addr;到站点的位置块。例如:/etc/nginx/sites-available/www.example.com。下面是一个服务器块示例。

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    location / {
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_pass http://127.0.1.1:3080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

重新启动nginx后,你将能够使用req访问你的节点/express应用程序路由中的ip。headers['x-real-ip'] || req.connection.remoteAddress;

我为此写了一个包。您可以将其用作表示中间件。我的软件包发布在这里:https://www.npmjs.com/package/express-ip

您可以使用

npm i express-ip

使用

const express = require('express');
const app = express();
const expressip = require('express-ip');
app.use(expressip().getIpInfoMiddleware);

app.get('/', function (req, res) {
    console.log(req.ipInfo);
});