Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

how to get external ip of the server from node.js

how to get external ip of the server from node.js

Problem

I'm using now.js and there's this line that refers to localhost. In order for someone to access the Server outside I need to modify localhost to be the current External ip of my computer(my ip is dynamic). Is there any way to detect the current external ip from the script?

window.now = nowInitialize("//localhost:8081", {});
Problem courtesy of: Wern Ancheta

Solution

You could ask an external service like this one (which is nice because it returns it without formatting).

To use it, you could use Node's built in http module:

require('http').request({
    hostname: 'fugal.org',
    path: '/ip.cgi',
    agent: false
}, function(res) {
    if(res.statusCode != 200) {
        throw new Error('non-OK status: ' + res.statusCode);
    }
    res.setEncoding('utf-8');
    var ipAddress = '';
    res.on('data', function(chunk) { ipAddress += chunk; });
    res.on('end', function() {
        // ipAddress contains the external IP address
    });
}).on('error', function(err) {
    throw err;
});

Keep in mind that external services can go down or change — this has happened once already, invalidating this answer. I've updated it, but this could happen again…

Solution courtesy of: icktoofay

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

how to get external ip of the server from node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×