Dou*_*las 2 heroku node.js socket.io
我最近在Heroku上使用Express和socket.io托管了我的第一个Node应用程序,需要找到客户端的IP地址.到目前为止,我已经尝试了socket.manager.handshaken[socket.id].address,socket.handshake.address并且socket.connection.address,两者都没有给出正确的地址.
应用程序:http://nes-chat.herokuapp.com/(还包含指向GitHub repo的链接)
要查看已连接用户的IP,请访问:http://nes-chat.herokuapp.com/users
谁知道问题是什么?
fri*_*ism 10
客户端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;
};
Run Code Online (Sandbox Code Playgroud)
您可以在一行中完成。
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);
}
Run Code Online (Sandbox Code Playgroud)
我喜欢将它添加到中间件并将 IP 作为我自己的自定义对象附加到请求中。
| 归档时间: |
|
| 查看次数: |
4752 次 |
| 最近记录: |