2013-01-17 45 views
2

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

應用:http://nes-chat.herokuapp.com/(還包含一個鏈接到GitHub庫)

要查看已連接的用戶的IP地址:http://nes-chat.herokuapp.com/users

任何人都知道問題是什麼?

+0

相關:http://stackoverflow.com/questions/6458083/socket-io-get-clients-ip-address – nha

回答

8

客戶端IP地址在X-Forwarded-For HTTP標頭中傳遞。我沒有測試過,但是它在確定客戶端IP時是looks like socket.io already takes this into account

你也應該能夠只是自己抓住它,這裏有一個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; 
}; 
+0

那完美。謝謝:) – Douglas

+0

不錯............ – Nav

+1

這裏說明了爲什麼只採取第一個可能是危險的:http://esd.io/blog/flask-apps-heroku-real- ip-spoofing.html(該值可以被操縱。) – caw

2

您可以在一行中做到這一點。

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連接請求作爲自己的定製對象。

0

以下爲我工作。

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

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