main.go 896 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "net"
  6. "time"
  7. )
  8. func main() {
  9. // 定义网段和子网掩码
  10. network := "192.168.1.0/22"
  11. var randomIP net.IP
  12. ip, ipNet, err := net.ParseCIDR(network)
  13. if err != nil {
  14. }
  15. net1 := ip.Mask(ipNet.Mask)
  16. minIP := net1.To4()
  17. maxIP := net.IPv4(minIP[0]|^ipNet.Mask[0], minIP[1]|^ipNet.Mask[1], minIP[2]|^ipNet.Mask[2], minIP[3]|^ipNet.Mask[3]).To4()
  18. // 生成随机种子
  19. rand.NewSource(time.Now().UnixNano())
  20. randomIP = generateRandomIP(minIP, maxIP)
  21. fmt.Printf(randomIP.String())
  22. }
  23. func generateRandomIP(min, max net.IP) net.IP {
  24. // IP地址是32位的,每位都是一个字节
  25. ip := make(net.IP, len(min))
  26. for i := range min {
  27. n := int(max[i] - min[i])
  28. if n == 0 {
  29. ip[i] = min[i]
  30. } else {
  31. ip[i] = byte(rand.Intn(n) + int(min[i]))
  32. }
  33. }
  34. if ip.Equal(min) || ip.Equal(max) {
  35. return generateRandomIP(min, max)
  36. }
  37. return ip
  38. }