我最近在Heroku上使用Express和socket.io托管了我的第一个Node应用程序,需要找到客户端的IP地址。到目前为止,我已经尝试了socket.manager.handshaken[socket.id].address
,socket.handshake.address
和socket.connection.address
,两者都没有给出正确的地址。
App:http://nes-chat.herokuapp.com/(还包含指向GitHub repo的链接)
查看已连接用户的IP:http://nes-chat.herokuapp.com/users
任何人都知道问题是什么?
答案 0 :(得分:9)
客户端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;
};
答案 1 :(得分:3)
你可以在一行中完成。
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作为我自己的自定义对象附加到请求中。
答案 2 :(得分:0)
以下对我有用。
Var client = require('socket.io').listen(8080).sockets;
client.on('connection',function(socket){
var clientIpAddress= socket.request.socket.remoteAddress;
});