如何从node.js获取服务器的外部ip

时间:2021-11-02 16:11:16

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?

我正在使用now.js,这条线引用了localhost。为了让某人能够访问外部服务器,我需要将localhost修改为我电脑的当前外部ip(我的ip是动态的)。有没有办法从脚本中检测当前的外部IP?

window.now = nowInitialize("//localhost:8081", {});

1 个解决方案

#1


3  

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:

要使用它,您可以使用Node内置的http模块:

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…

请记住,外部服务可能会崩溃或发生变化 - 这已经发生过一次,使这个答案无效。我已经更新了,但这可能会再次发生......

#1


3  

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:

要使用它,您可以使用Node内置的http模块:

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…

请记住,外部服务可能会崩溃或发生变化 - 这已经发生过一次,使这个答案无效。我已经更新了,但这可能会再次发生......