6

我最近在 Heroku 上使用 Express 和 socket.io 托管了我的第一个 Node 应用程序,并且需要找到客户端的 IP 地址。到目前为止,我已经尝试过socket.manager.handshaken[socket.id].address,socket.handshake.addresssocket.connection.address,两者都没有给出正确的地址。

应用程序:http: //nes-chat.herokuapp.com/(还包含指向 GitHub 存储库的链接)

查看已连接用户的 IP:http: //nes-chat.herokuapp.com/users

有谁知道问题是什么?

4

3 回答 3

12

客户端 IP 地址在X-Forwarded-ForHTTP 标头中传递。我还没有测试过,但看起来 socket.io在确定客户端 IP 时已经考虑到了这一点。

你也应该能够自己抓住它,这里有一个指南

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;
};
于 2013-01-17T15:56:58.543 回答
5

您可以在一行中完成。

function getClientIp(req) {
    // The X-Forwarded-For request header helps you identify the IP address of a client when you use HTTP/HTTPS load balancer.
    // http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-for
    // If the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"]
    // http://expressjs.com/4x/api.html#req.ips
    var ip = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0] : req.connection.remoteAddress;
    console.log('IP: ', ip);
}

我喜欢将它添加到中间件并将 IP 作为我自己的自定义对象附加到请求中。

于 2014-05-23T17:58:36.843 回答
0

以下对我有用。

Var client = require('socket.io').listen(8080).sockets;

client.on('connection',function(socket){ 
var clientIpAddress= socket.request.socket.remoteAddress;
});
于 2014-06-03T02:35:03.013 回答