现在在Node.js中找到默认网关IP地址的最佳方法是什么?
os.networkInterfaces()
未提供此信息。
唯一的想法是解析子进程route -n
的 stdout :
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
答案 0 :(得分: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.'
})
答案 1 :(得分:0)
因为所有其他方式都不起作用,而且 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();
});
})();
}