lcg unique distribution improvement

This commit is contained in:
delorean 2024-11-22 17:45:33 -06:00
parent 6307804204
commit a344a9caae

View File

@ -1,6 +1,8 @@
package common
import (
"crypto/rand"
"encoding/binary"
"fmt"
"math/big"
"net"
@ -19,6 +21,14 @@ func toip(num uint32) string {
num&255)
}
func seed() int64 {
var n int64
if err := binary.Read(rand.Reader, binary.LittleEndian, &n); err != nil {
return 1337
}
return n
}
// per-cidr linear congruential generator for efficient randomized target ip ordering, ty claude
func LCG(cidr string, out chan<- string) {
// lcg constants
@ -27,11 +37,10 @@ func LCG(cidr string, out chan<- string) {
_, ipnet, _ := net.ParseCIDR(cidr)
start := iptouint(ipnet.IP)
ones, bits := ipnet.Mask.Size()
addrcount := new(big.Int).Lsh(big.NewInt(1), uint(bits-ones))
x := uint64(start)
x := uint64(seed()) ^ uint64(start) // seed for unique randomization per execution
m := uint64(addrcount.Uint64())
for i := uint64(0); i < m; i++ {