package main import ( "fmt" "net" "strconv" ) // ipToInt 将IP地址转换为整数 func ipToInt(ip net.IP) uint32 { ip = ip.To4() return uint32(ip[0])<<24 + uint32(ip[1])<<16 + uint32(ip[2])<<8 + uint32(ip[3]) } // intToIP 将整数转换为IP地址 func intToIP(n uint32) net.IP { return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) } // generateIPs 生成从startIP到endIP的所有IP地址 func generateIPs(startIP, endIP string) ([]string, error) { start := net.ParseIP(startIP) end := net.ParseIP(endIP) if start == nil || end == nil { return nil, fmt.Errorf("invalid IP address") } startInt := ipToInt(start) endInt := ipToInt(end) if startInt > endInt { return nil, fmt.Errorf("start IP must be less than or equal to end IP") } var ips []string for ip := startInt; ip <= endInt; ip++ { ips = append(ips, intToIP(ip).String()) } return ips, nil } func main() { startIP := "10.10.1.200" endIP := "10.10.2.50" _, ipNet, err := net.ParseCIDR("10.10.1.1/22") if err != nil { panic(err) } fmt.Println(strconv.Itoa(int(ipNet.Mask[0])) + "." + strconv.Itoa(int(ipNet.Mask[1])) + "." + strconv.Itoa(int(ipNet.Mask[2])) + "." + strconv.Itoa(int(ipNet.Mask[3]))) ips, err := generateIPs(startIP, endIP) if err != nil { fmt.Println("Error:", err) return } for _, ip := range ips { fmt.Println(ip) } }