Hello,
How to get client IP address at server side. I have tried “this.connection.clientAddress” but it’s not giving me proper public ip adress as from below snippet.
$.getJSON("http://jsonip.com?callback=?", function (data) {
console.log("Your ip: " + data.ip);
});
by using “this.connection.clientAddress” I am getting 127.0.0.1 as I am running my site on localhost:3000.
So, please provide me solution.
this.connection.clientAddress
is the proper way to get the client ip.
See http://ip-test-2.meteor.com/
Here’s the code https://github.com/krishamoud/meteor-ip-test
2 Likes
Hello khamoud,
By running http://ip-test-2.meteor.com/, I am getting IP address.
But I have created one meteor project and it’s running on localhost:3000, while writing this.connection.clientAddress at server side I am getting 127.0.0.1 IP address which is not correct, so could you please elaborate it more.
Thanks for your quick reply.
127.0.0.1
is the IPv4 version of localhost
, since localhost
is not a valid IPv4 address. The reason you can use localhost
is because you have a host line in your /etc/hosts
file mapping localhost
to 127.0.0.1
.
You cannot get your external IP-address when you’re running locally without using a workaround, which you can do with the HTTP library:
meteor add http
var res = HTTP.get('http://jsonip.com?callback=?');
console.log(res.data.ip); // Public IP (of server)
Note that when you deploy your app to production, you should replace that with this.connection.clientAddress
since it will work as it should.
A thing you could do to avoid having to change things each time you deploy is to read the NODE_ENV
environment variable.
var env = process.env.NODE_ENV;
var ip;
if (env === 'production') {
ip = this.connection.clientAddress;
} else {
ip = HTTP.get('http://jsonip.com?callback=?').data.ip;
}
This will require you to set the NODE_ENV
to production
every time you deploy, which is of course something you should always do (don’t know why Meteor docs on deploy doesn’t include that). To do this you could simply run export NODE_ENV=production
on your server before starting your Meteor app.
3 Likes
Thanks svenskunganka,
I really appreciate your reply.
Thanks again.
1 Like
Thanks! This was the right answer for me.