-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathip.js
29 lines (24 loc) · 861 Bytes
/
ip.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import ip from 'ipaddr.js'
import { strict as assert } from 'node:assert'
import { randomBytes } from 'node:crypto'
function parseCIDR(cidr) {
const [ addr, prefix ] = ip.parseCIDR(cidr)
const bytes = addr.toByteArray();
return {
bytes: bytes.slice(0, Math.ceil(prefix / 8)),
available: bytes.length * 8 - prefix,
}
}
function generateRandomIPArray({ bytes, available }, count = available) {
assert(Array.isArray(bytes))
assert(count <= available)
if (count % 8) throw 'currently, only prefixes that are multiples of 8 are supported'
return bytes
.concat([...randomBytes(count / 8)])
.concat(Array((available - count) / 8).fill(0))
}
export function generateRandomIP(cidr, count) {
return ip.fromByteArray(
generateRandomIPArray(parseCIDR(cidr), count)
).toString();
}