How to get the user IP address in Meteor server?

前端 未结 6 808
情书的邮戳
情书的邮戳 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:42

    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.

提交回复
热议问题