network.go 847 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package ganserv
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "net"
  6. "time"
  7. )
  8. //Get a random free IP from the pool
  9. func (n *Network) GetRandomFreeIP() (net.IP, error) {
  10. // Get all IP addresses in the subnet
  11. ips, err := GetAllAddressFromCIDR(n.CIDR)
  12. if err != nil {
  13. return nil, err
  14. }
  15. // Filter out used IPs
  16. usedIPs := make(map[string]bool)
  17. for _, node := range n.Nodes {
  18. usedIPs[node.ManagedIP.String()] = true
  19. }
  20. availableIPs := []string{}
  21. for _, ip := range ips {
  22. if !usedIPs[ip] {
  23. availableIPs = append(availableIPs, ip)
  24. }
  25. }
  26. // Randomly choose an available IP
  27. if len(availableIPs) == 0 {
  28. return nil, fmt.Errorf("no available IP")
  29. }
  30. rand.Seed(time.Now().UnixNano())
  31. randIndex := rand.Intn(len(availableIPs))
  32. pickedFreeIP := availableIPs[randIndex]
  33. return net.ParseIP(pickedFreeIP), nil
  34. }