【问题标题】:What's the best way to find default gateway IP in Node.js?在 Node.js 中查找默认网关 IP 的最佳方法是什么?
【发布时间】:2017-06-01 09:55:02
【问题描述】:

如今在 Node.js 中查找默认网关 IP 地址的最佳方法是什么?

os.networkInterfaces() 不提供此信息。

想到的唯一想法是解析子进程route -nstdout

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.2     0.0.0.0         UG    100    0        0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

【问题讨论】:

标签: node.js ip gateway


【解决方案1】:

使用网络包:https://www.npmjs.com/package/network

;)

network.get_gateway_ip(function(err, ip) {
  console.log(err || ip); // err may be 'No active network interface found.' 
})

【讨论】:

【解决方案2】:

因为所有其他方法都行不通,而且 JavaScript 非常有限。这是我的一段代码。我不太擅长javas-但逻辑是,如果IP在特定时间内响应,那么它就是网关IP。如果不是,那就不是。列表中的网关 IP 越多越好,但是使用此脚本仍然存在缺陷。由于大多数网关 IP 实际上被其他网络上的设备占用。这可能会导致问题并且结果可能不准确。

var responses = [];
var ips = ["192.168.1.1", "192.168.0.1", "10.0.0.138", "192.168.2.1", "192.168.254.254", "10.0.1.1", "192.168.3.1", "10.10.1.1", "10.0.0.1", "10.0.0.2", "10.1.1.1", "192.168.11.1", "192.168.0.30", "192.168.0.50", "192.168.0.10", "192.168.0.101", "192.168.15.1", "10.90.90.90", "192.168.8.1", "192.168.86.1", "192.168.100.1", "192.168.123.254", "192.168.16.1", "192.168.10.1", "192.168.20.1", "192.168.30.1", "192.168.62.1", "192.168.102.1", "192.168.0.227", "192.168.10.50", "10.1.10.1", "192.168.0.3", "192.168.168.168", "192.168.50.1", "192.168.55.1", "192.168.251.1", "192.168.0.254", "192.168.0.100", "192.168.10.10", "192.168.10.100", "192.168.223.100", "200.200.200.5", "192.168.4.1", "192.168.100.100", "192.168.2.254"];
var length = ips.length

for (var i = 0; i < length; i++){
    (async function(){
        var connection = new WebSocket('ws://' + ips[i] + ':80');
        await new Promise (function(res){
                var timeout = setTimeout(function() {
                                console.log("Socket connection timeout", connection.readyState);
                                console.log(connection.url);
                                if (connection.readyState == 3){
                                    responses.push('valid')
                                    alert(connection.url);
                                } else {
                                    responses.push('invalid')
                                }
                                connection.close();
                }, 5000);
                res();
        });
    })();

}

【讨论】:

    【解决方案3】:

    在 Ubuntu 中我尝试这样

    const spawn = require('child_process').spawnSync;
    
    const child = spawn('bash', ['-c', 'ip r']).stdout.toString();
    const gateway = child.match(/default via (.*?)\s/)[1];
    console.log(gateway);
    

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 1970-01-01
      • 2012-01-28
      • 2023-03-24
      • 2011-06-07
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 2016-01-08
      相关资源
      最近更新 更多