How to get the user IP address in Meteor server?

杀马特。学长 韩版系。学妹 提交于 2019-12-17 07:19:13

问题


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 users subscribing to a mailing list, or just doing anything important).

I know that the IP address 'seen' by the server can be different than the real source address when there are reverse proxies involved. In such situations, X-Forwarded-For header should be parsed to get the real public IP address of the user. Note that parsing X-Forwarded-For should not be automatic (see http://www.openinfo.co.uk/apache/index.html for a discussion of potential security issues).

External reference: This question came up on the meteor-talk mailing list in august 2012 (no solution offered).


回答1:


1 - Without a http request, in the functions you should be able to get the clientIP with:

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

2 - With a http request and using iron-router and its Router.map function:

In the action function of the targeted route use:

clientIp = this.request.connection.remoteAddress;

3 - using Meteor.onConnection function:

Meteor.onConnection(function(conn) {
    console.log(conn.clientAddress);
});



回答2:


Similar to the TimDog answer but works with newer versions of Meteor:

var Fiber = Npm.require('fibers');

__meteor_bootstrap__.app
  .use(function(req, res, next) {
    Fiber(function () {
      console.info(req.connection.remoteAddress);
      next();
    }).run();
  });

This needs to be in your top-level server code (not in Meteor.startup)




回答3:


This answer https://stackoverflow.com/a/22657421/2845061 already does a good job on showing how to get the client IP address.

I just want to note that if your app is served behind proxy servers (usually happens), you will need to set the HTTP_FORWARDED_COUNT environment variable to the number of proxies you are using.

Ref: https://docs.meteor.com/api/connections.html#Meteor-onConnection




回答4:


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.




回答5:


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.




回答6:


Here's a way that has worked for me to get a client's IP address from anywhere on the server, without using additional packages. Working in Meteor 0.7 and should work in earlier versions as well.

On the client, get the socket URL (unique) and send it to the server. You can view the socket URL in the web console (under Network in Chrome and Safari).

socket_url = Meteor.default_connection._stream.socket._transport.url
Meteor.call('clientIP', socket_url)

Then, on the server, use the client's socket URL to find their IP in Meteor.server.sessions.

sr = socket_url.split('/')
socket_path = "/"+sr[sr.length-4]+"/"+sr[sr.length-3]+"/"+sr[sr.length-2]+"/"+sr[sr.length-1]
_.each(_.values(Meteor.server.sessions), (session) ->
    if session.socket.url == socket_path
        user_ip = session.socket.remoteAddress
)

user_ip now contains the connected client's IP address.



来源:https://stackoverflow.com/questions/14843232/how-to-get-the-user-ip-address-in-meteor-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!