gpt4 book ai didi

node.js - Nodejs区分http请求;具有相同公共(public) IP 的多个设备

转载 作者:可可西里 更新时间:2023-11-01 17:17:44 24 4
gpt4 key购买 nike

你好!我正在尝试用 Node 表示通过 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 地址只是网络配置错误的情况?

谢谢!

最佳答案

如果您使用 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 对于某些用例会更好。

关于node.js - Nodejs区分http请求;具有相同公共(public) IP 的多个设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com