문제

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", {});
도움이 되었습니까?

해결책

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…

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top