Nodejs区分http请求;具有相同 public IP 的多个设备

Nodejs distinguishing http requests; multiple devices with same public IP

你好!我正在尝试用节点表示通过 http 的客户端连接。现在我有类似的东西:

let names = [ 'john', 'margaret', 'thompson', /* ... tons more ... */ ];
let nextNameInd = 0;   

let clientsIndexedByIp = {};
let createNewClient = ip => {
  return {
    ip,
    name: names[nextNameInd++],
    numRequests: 0
  };
};

require('http').createServer((req, res) => {

  let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

  // If this is a connection we've never seen before, create a client for it
  if (!clientsIndexedByIp.hasOwnProperty(ip)) {
    clientsIndexedByIp[ip] = createNewClient(ip);
  }

  let client = clientsIndexedByIp[ip];
  client.numRequests++;

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(client));

}).listen(80, '<my public ip>', 511);

我运行这个代码在一些远程服务器上,它工作正常;我可以查询该服务器并获得预期的响应。但我有一个问题:我的笔记本电脑和智能手机都连接到同一个 wifi;如果我从我的笔记本电脑和智能手机查询该服务器,服务器认为这两个设备具有相同的 IP 地址,并且它只为它们创建一个 "client" 对象。

例如每个响应的 "name" 参数都相同。

在我的笔记本电脑和智能手机上检查 whatsmyip.org 显示相同的 IP 地址 - 这让我感到惊讶,因为我对 IP 的理解是错误的。直到此时我还以为所有设备都有一个唯一的 IP。

我希望不同的设备与不同的客户端相关联,即使两个设备在同一个 wifi 网络上也是如此。我假设我用来消除设备歧义的数据,仅它们的请求 IP (req.headers['x-forwarded-for'] || req.connection.remoteAddress) 是不够的。

如何区分连接到同一路由器的多个设备? req 对象中是否有一些额外的数据允许这样做?

或者我的笔记本电脑和智能手机具有相同的 IP 地址只是网络配置错误的情况?

谢谢!

如果您使用 express-fingerprint 模块,这将适用于大多数用例,例如:

const express = require('express');
const app = express();
const port = 3000;
var Fingerprint = require('express-fingerprint')

app.use(Fingerprint( { parameters:[
    Fingerprint.useragent,
    Fingerprint.geoip ]
}));

app.get('/test', function(req, res){
    console.log("Client fingerprint hash: ", req.fingerprint.hash);
    res.send("Your client Id: " + req.fingerprint.hash);
});

app.listen(port);

每个客户端都有一个唯一的哈希值,您可以使用它来识别它们。值得理解的是,这种方法会有局限性,并且为客户端分配 cookie 对于某些用例会更好。