How to get the user IP address in Meteor server?

前端 未结 6 806
情书的邮戳
情书的邮戳 2020-11-30 03:03

I would like to get the user IP address in my meteor application, on the server side, so that I can log the IP address with a bunch of things (for example: non-registered us

6条回答
  •  粉色の甜心
    2020-11-30 03:59

    You could do this in your server code:

    Meteor.userIPMap = [];
    __meteor_bootstrap__.app.on("request", function(req, res) {
        var uid = Meteor.userId();
        if (!uid) uid = "anonymous";
        if (!_.any(Meteor.userIPMap, function(m) { m.userid === uid; })) {
            Meteor.userIPMap.push({userid: uid, ip: req.connection.remoteAddress });
        }
    });
    

    You'll then have a Meteor.userIPMap with a map of userids to ip addresses (to accommodate the x-forwarded-for header, use this function inside the above).

    Three notes: (1) this will fire whenever there is a request in your app, so I'm not sure what kind of performance hit this will cause; (2) the __meteor_bootstrap__ object is going away soon I think with a forthcoming revamped package system; and (3) the anonymous user needs better handling here..you'll need a way to attach an anonymous user to an IP by a unique, persistent constraint in their request object.

提交回复
热议问题