How to get the user IP address in Meteor server?

前端 未结 6 805
情书的邮戳
情书的邮戳 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 04:08

    You have to hook into the server sessions and grab the ip of the current user:

    Meteor.userIP = function(uid) {
          var k, ret, s, ss, _ref, _ref1, _ref2, _ref3;
          ret = {};
          if (uid != null) {
                _ref = Meteor.default_server.sessions;
                for (k in _ref) {
                      ss = _ref[k];
                      if (ss.userId === uid) {
                            s = ss;
                      }
                }
                if (s) {
                      ret.forwardedFor = ( _ref1 = s.socket) != null ? 
                            ( _ref2 = _ref1.headers) != null ? 
                            _ref2['x-forwarded-for'] : void 0 : void 0;
                      ret.remoteAddress = ( _ref3 = s.socket) != null ? 
                            _ref3.remoteAddress : void 0;
                }
          }
          return ret.forwardedFor ? ret.forwardedFor : ret.remoteAddress;
    };
    

    Of course you will need the current user to be logged in. If you need it for anonymous users as well follow this post I wrote.

    P.S. I know it's an old thread but it lacked a full answer or had code that no longer works.

提交回复
热议问题