main.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "strconv"
  6. )
  7. // ipToInt 将IP地址转换为整数
  8. func ipToInt(ip net.IP) uint32 {
  9. ip = ip.To4()
  10. return uint32(ip[0])<<24 + uint32(ip[1])<<16 + uint32(ip[2])<<8 + uint32(ip[3])
  11. }
  12. // intToIP 将整数转换为IP地址
  13. func intToIP(n uint32) net.IP {
  14. return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  15. }
  16. // generateIPs 生成从startIP到endIP的所有IP地址
  17. func generateIPs(startIP, endIP string) ([]string, error) {
  18. start := net.ParseIP(startIP)
  19. end := net.ParseIP(endIP)
  20. if start == nil || end == nil {
  21. return nil, fmt.Errorf("invalid IP address")
  22. }
  23. startInt := ipToInt(start)
  24. endInt := ipToInt(end)
  25. if startInt > endInt {
  26. return nil, fmt.Errorf("start IP must be less than or equal to end IP")
  27. }
  28. var ips []string
  29. for ip := startInt; ip <= endInt; ip++ {
  30. ips = append(ips, intToIP(ip).String())
  31. }
  32. return ips, nil
  33. }
  34. func main() {
  35. startIP := "10.10.1.200"
  36. endIP := "10.10.2.50"
  37. _, ipNet, err := net.ParseCIDR("10.10.1.1/22")
  38. if err != nil {
  39. panic(err)
  40. }
  41. 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])))
  42. ips, err := generateIPs(startIP, endIP)
  43. if err != nil {
  44. fmt.Println("Error:", err)
  45. return
  46. }
  47. for _, ip := range ips {
  48. fmt.Println(ip)
  49. }
  50. }