簡體   English   中英

如何從node.js獲取服務器的外部IP

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

我正在使用now.js,並且此行引用了localhost。 為了使某人可以訪問外部服務器,我需要將localhost修改為計算機的當前外部IP(我的IP是動態的)。 有什么辦法可以從腳本中檢測當前的外部IP?

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

你可以問這樣一個外部服務這一項 (這是很好的,因為它返回它不帶格式)。

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

請記住,外部服務可能會下降或發生變化-這已經發生過一次,從而使該答案無效。 我已經更新了,但是這種情況可能會再次發生…

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM