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

2023-12-30

你好!我正在尝试使用 Node.js 来表示通过 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 地址,并且它只会为这两个设备创建一个“客户端”对象。

例如。每个响应的“名称”参数都是相同的。

在我的笔记本电脑和智能手机上检查 Whatsmyip.org 时显示了相同的 IP 地址 - 这让我感到惊讶,因为我对 IP 的理解被证明是错误的。到目前为止,我认为所有设备都有一个唯一的 IP。

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

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

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

Thanks!


如果您使用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 分配给客户端对于某些用例会更有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Nodejs区分http请求;多个设备具有相同的公共IP 的相关文章

随机推荐