你好!我正在尝试使用 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!