【发布时间】:2019-05-17 20:23:25
【问题描述】:
我正在尝试在给定 IP 地址子网的情况下生成一个随机 IP 地址。有大量资源可用于生成随机 IP,但我要求它从特定子网中生成。
我使用了一个名为 netmask 的 npm 模块 - 但是实现绝对不优雅。任何人都可以请给出一些巧妙的指针吗?
var netmask = require("netmask").Netmask
var block = new netmask('10.0.0.0/24')
console.log(block) // gives block details
var blockSize = block.size - 1 ;
var randomIndex = Math.floor(Math.random() * blockSize ) +1; // generate a random number less than the size of the block
console.log("randomIndex is: " + randomIndex);
block.forEach(function(ip, long, index){
if(index == randomIndex){
console.log('IP: ' + ip)
console.log('INDEX: ' + index)
// cannot break! this is a forEach :(
}
});
【问题讨论】:
标签: javascript npm ip-address ipv4 subnet