我最近在 Heroku 上使用 Express 和 socket.io 托管了我的第一个 Node 应用程序,需要找到客户端的 IP 地址。到目前为止,我已经尝试了 socket.manager.handshaken[socket.id].address
、socket.handshake.address
和 socket.connection.address
,两者都没有给出正确的地址。
应用程序:http://nes-chat.herokuapp.com/ (还包含指向 GitHub 存储库的链接)
查看已连接用户的 IP:http://nes-chat.herokuapp.com/users
有人知道问题出在哪里吗?
最佳答案
客户端 IP 地址在 X-Forwarded-For
HTTP header 中传递。我没有测试过,但它 looks like socket.io already takes this into account在确定客户端 IP 时。
您也应该可以自己获取,这里是 guide :
function getClientIp(req) {
var ipAddress;
// Amazon EC2 / Heroku workaround to get real client IP
var forwardedIpsStr = req.header('x-forwarded-for');
if (forwardedIpsStr) {
// 'x-forwarded-for' header may return multiple IP addresses in
// the format: "client IP, proxy 1 IP, proxy 2 IP" so take the
// the first one
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
if (!ipAddress) {
// Ensure getting client IP address still works in
// development environment
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
关于node.js - 如何将客户端的正确 IP 地址获取到托管在 Heroku 上的 Node socket.io 应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14382725/