package main

import (
	"fmt"
	"math/rand"
	"net"
	"time"
)

func main() {
	// 定义网段和子网掩码
	network := "192.168.1.0/22"
	var randomIP net.IP

	ip, ipNet, err := net.ParseCIDR(network)
	if err != nil {
	}
	net1 := ip.Mask(ipNet.Mask)
	minIP := net1.To4()
	maxIP := net.IPv4(minIP[0]|^ipNet.Mask[0], minIP[1]|^ipNet.Mask[1], minIP[2]|^ipNet.Mask[2], minIP[3]|^ipNet.Mask[3]).To4()
	// 生成随机种子
	rand.NewSource(time.Now().UnixNano())
	randomIP = generateRandomIP(minIP, maxIP)
	fmt.Printf(randomIP.String())
}

func generateRandomIP(min, max net.IP) net.IP {
	// IP地址是32位的，每位都是一个字节
	ip := make(net.IP, len(min))
	for i := range min {
		n := int(max[i] - min[i])
		if n == 0 {
			ip[i] = min[i]
		} else {
			ip[i] = byte(rand.Intn(n) + int(min[i]))
		}
	}
	if ip.Equal(min) || ip.Equal(max) {
		return generateRandomIP(min, max)
	}
	return ip
}
