包含具体多少ip要输出为数组
时间: 2024-03-09 11:45:57 浏览: 20
如果要输出包含的 IP 数组,可以修改 `calculateSubnet` 函数,添加一个 `ips` 属性,用来存储 IP 地址数组。修改后的代码如下:
```javascript
function calculateSubnet(ipRange) {
const [startIp, endIp] = ipRange.split('/');
const [s1, s2, s3, s4] = startIp.split('.').map(Number);
const [e1, e2, e3, e4] = endIp.split('.').map(Number);
const numIps = (e1 - s1) * 256 * 256 * 256 +
(e2 - s2) * 256 * 256 +
(e3 - s3) * 256 +
(e4 - s4) +
1;
const prefixLength = 32 - Math.floor(Math.log2(numIps));
const subnetMask = [
0xff << (8 - Math.min(8, prefixLength)),
0xff << (8 - Math.min(16, prefixLength)),
0xff << (8 - Math.min(24, prefixLength)),
0xff << (8 - Math.min(32, prefixLength)),
];
const networkAddress = [
s1 & subnetMask[0],
s2 & subnetMask[1],
s3 & subnetMask[2],
s4 & subnetMask[3],
].join('.');
const broadcastAddress = [
networkAddress.split('.').map(Number).map((n, i) => n | ~subnetMask[i] & 0xff),
].join('.');
const ips = [...Array(numIps).keys()].map(n => {
const ip = [
s1 + Math.floor(n / 256 / 256 / 256),
s2 + Math.floor(n / 256 / 256) % 256,
s3 + Math.floor(n / 256) % 256,
s4 + n % 256,
];
return ip.join('.');
});
return {
subnetMask: subnetMask.join('.'),
networkAddress,
broadcastAddress,
numIps,
ips,
};
}
console.log(calculateSubnet('192.168.2.1/192.168.3.142').ips);
```
输出结果为:
```json
[
"192.168.2.1",
"192.168.2.2",
"192.168.2.3",
"192.168.2.4",
"192.168.2.5",
"192.168.2.6",
"192.168.2.7",
"192.168.2.8",
"192.168.2.9",
"192.168.2.10",
// ...
"192.168.3.138",
"192.168.3.139",
"192.168.3.140",
"192.168.3.141",
"192.168.3.142"
]
```
其中,`ips` 数组按照 IP 地址从小到大排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)