簡體   English   中英

如何將客戶端的正確IP地址轉換為Heroku上托管的Node socket.io應用程序?

[英]How to get the correct IP address of a client into a Node socket.io app hosted on Heroku?

我最近在Heroku上使用Express和socket.io托管了我的第一個Node應用程序,需要找到客戶端的IP地址。 到目前為止,我已經嘗試過socket.manager.handshaken[socket.id].addresssocket.handshake.addresssocket.connection.address ,它們都沒有給出正確的地址。

應用程序: http//nes-chat.herokuapp.com/ (還包含指向GitHub repo的鏈接)

要查看已連接用戶的IP,請訪問: http//nes-chat.herokuapp.com/users

誰知道問題是什么?

客戶端IP地址在X-Forwarded-For HTTP標頭中傳遞。 我還沒有測試過,但看起來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;
};

你可以在一行中完成。

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作為我自己的自定義對象附加到請求。

以下對我有用。

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

client.on('connection',function(socket){ 
var clientIpAddress= socket.request.socket.remoteAddress;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM