如何在Meteor中获取客户端IP地址?

10

这似乎是一个非常基础的问题,没有优雅的解决方案/答案。
如何从(1)服务器或(2)客户端访问客户端(远程)IP地址?


请参见:https://dev59.com/6HVD5IYBdhLWcg3wDXJ3 - Dominic Sore
不知道cgi-bin是什么,也不知道如何将其用于此目的... :/ - Chet
4个回答

18

获取客户端IP:

在没有HTTP请求的情况下,在函数中,您应该能够使用以下代码获取客户端IP:

clientIP = this.connection.clientAddress;
//EX: you declare a submitForm function with Meteor.methods and 
//you call it from the client with Meteor.call().
//In submitForm function you will have access to the client address as above

通过http请求,使用iron-router及其Router.map功能:

在目标路由的操作函数中使用:

clientIp = this.request.connection.remoteAddress;

你好Florin,提一下这个问题是这个的完美副本怎么样? - Dan Dascalescu
1
我完全同意,当时我想留下评论而不是回答,但我没有足够的声望点数(在不属于您的问题/答案上发布评论需要50个或更多声望点) - Florin Dobre
这仅在版本0.7.1.1之后可用,对于那些运行在旧版本上的应用程序,就像我一样。 - user2602152

7

正如Florin所提到的,现在这一切都与Meteor集成在一起,而不是我们自己做的黑暗时代。但是,我另外包装了一个跟踪所有打开连接并允许您查询其IP的软件包:https://github.com/mizzao/meteor-user-status。它还可以执行其他有用的操作。


2
在客户端
headers = {
    list: {},
    get: function(header, callback) {
        return header ? this.list[header] : this.list;
    }
}

Meteor.call('getReqHeaders', function(error, result) {
    if (error) {
        console.log(error);
    }
    else {
        headers.list = result;
    }
});

在服务器上:

headers = {
    list: {},
    get: function(header) {
        return header ? this.list[header] : this.list;
    }
};

var app = typeof WebApp != 'undefined' ? WebApp.connectHandlers : __meteor_bootstrap__.app;
app.use(function(req, res, next) {
    reqHeaders = req.headers;
    return next();
});

Meteor.methods({
    'getReqHeader': function(header) {
        return reqHeaders[header];
    },
    'getReqHeaders': function () {
        return reqHeaders;
    },
});

1
现在这已经过时了。客户端IP现在通过核心的clientAddress提供 - http://docs.meteor.com/#/full/meteor_onconnection - Dan Dascalescu

1
你可以使用这个包:https://github.com/gadicohen/meteor-headers。它可以在客户端和服务器端获取头部信息。
如果不想使用包,你可以从上面的代码中“获得灵感”,需要记住的是,在0.6.5之前我们使用了“隐藏”的__meteor_bootstrap__.app,在0.6.5之后推荐使用WebApp.connectHandler

1
这是一个非常好的解决方案 :) - Chet
1
在服务器上似乎没有完全运行 - 可能是我做错了:https://github.com/gadicohen/meteor-headers/issues/2 - Chet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接