2012-04-01 98 views
0

我使用now.js,并且有一行指向localhost。为了让某人访问外部服务器,我需要将localhost修改为我的计算机的当前外部IP(我的IP是动态的)。有没有办法从脚本中检测当前的外部IP?如何从node.js获得服务器的外部ip

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

回答

3

你可以问一个外部服务,如this one(这很好,因为它没有格式化就返回它)。

要使用它,你可以使用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; 
}); 

请记住,外部服务可以去或改变 - 这已经发生过一次了,这种无效答案。我已经更新了,但是这可能会再次发生...

+0

我该如何获得从网站返回的IP? – 2012-04-01 07:33:35

+0

@Kyoka:我添加了一些代码。看我的编辑。 – icktoofay 2012-04-01 21:09:38

+0

这将不再工作,该网站现在显示图像中的IP地址。 – 2013-07-29 04:46:44

相关问题