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

2019-06-10 15:52发布

问题:

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", {});

回答1:

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…