Skip to content

Instantly share code, notes, and snippets.

@dontlaugh
Created August 14, 2020 15:40
Show Gist options
  • Save dontlaugh/bec85f9792613a0898eb4d558c146d02 to your computer and use it in GitHub Desktop.
Save dontlaugh/bec85f9792613a0898eb4d558c146d02 to your computer and use it in GitHub Desktop.
generate random ipv4 address in go
func randomIPFromRange(cidr string) (net.IP, error) {
GENERATE:
ip, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
// The number of leading 1s in the mask
ones, _ := ipnet.Mask.Size()
quotient := ones / 8
remainder := ones % 8
// create random 4-byte byte slice
r := make([]byte, 4)
rand.Read(r)
for i := 0; i <= quotient; i++ {
if i == quotient {
shifted := byte(r[i]) >> remainder
r[i] = ^ipnet.IP[i] & shifted
} else {
r[i] = ipnet.IP[i]
}
}
ip = net.IPv4(r[0], r[1], r[2], r[3])
if ip.Equal(ipnet.IP) /*|| ip.Equal(broadcast) */ {
// we got unlucky. The host portion of our ipv4 address was
// either all 0s (the network address) or all 1s (the broadcast address)
goto GENERATE
}
return ip, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment