簡體   English   中英

如何在偵聽時獲取Restify服務器的確切IP地址?

[英]How to get the exact IP address of the Restify server on listen?

請考慮以下用於其余API節點服務器的代碼。

var restify = require('restify');

var server = restify.createServer();

server.get('/echo/:name', function (req, res, next) {
  res.send({name: req.params.name});
  next();
});

server.listen(8080, function () {
  console.log('%s listening at %s', server.name, server.url);
});

使用節點運行該服務器:

$ node echo.js
restify listening at http://0.0.0.0:8080

它顯示0.0.0.0這是錯誤的。

任何人都可以在開啟時如何控制台登錄服務器的確切IP?

謝謝


更新 :在執行下面的代碼時,我得到了下面提到的輸出,這再次變得困難,選擇哪個IP?

  rest_server.listen(config.appPort, function () { var adrs = require('os').networkInterfaces(); console.log(adrs); console.log('%s listening at %s', rest_server.name, rest_server.url); }); 

輸出:

 { 'Local Area Connection': [ { address: '192.168.3.60', family: 'IPv4', internal : false } ], 'Loopback Pseudo-Interface 1': [ { address: '::1', family: 'IPv6', internal: true }, { address: '127.0.0.1', family: 'IPv4', internal: true } ], 'isatap.TEST.ORG': [ { address: 'fe80::5efe:c0a8:33c', family: 'IPv6', internal: false } ] } restify listening at http://0.0.0.0:8080 

您可以將實際地址設置為listen方法,請參閱

http://mcavage.github.io/node-restify/#Server-APIhttp://nodejs.org/docs/latest/api/net.html#net_server_listen_path_callback

server.address()可能會返回服務器綁定的地址:

http://nodejs.org/docs/latest/api/net.html#net_server_address

有相同的問題並找出問題,基本上你可以傳遞另一個參數到.listen()函數,這應該是你的服務器IP地址

server.listen(port, [host], [backlog], [callback])


server.listen(port, YOUR IP ADDRESS, function(){ });

為了獲得您的服務器IP地址,請在終端中執行“traceroute www.WEBSITE_URL.com”。

如果您還有問題,請告訴我。

謝謝馬赫迪

得到了一些解決方案,如下所示。

總是歡迎任何改進。

var osDetails = require('os');

function getDynamicIP(calbck) {
    var ip;
    try {
        var adrs = osDetails.networkInterfaces();
        for (key in adrs) {
            if (adrs.hasOwnProperty(key)) {
                if (adrs[key][0].internal === false && adrs[key][0].family === 'IPv4') {
                    ip = adrs[key][0].address;
                    break;
                }
            }
        }
    }
    catch (e) {
        return calbck(e, null);
    }
    return calbck(null, ip);
}

暫無
暫無

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

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