utils.go 1010 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package ganserv
  2. import (
  3. "net"
  4. )
  5. //Generate all ip address from a CIDR
  6. func GetAllAddressFromCIDR(cidr string) ([]string, error) {
  7. ip, ipnet, err := net.ParseCIDR(cidr)
  8. if err != nil {
  9. return nil, err
  10. }
  11. var ips []string
  12. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
  13. ips = append(ips, ip.String())
  14. }
  15. // remove network address and broadcast address
  16. return ips[1 : len(ips)-1], nil
  17. }
  18. func inc(ip net.IP) {
  19. for j := len(ip) - 1; j >= 0; j-- {
  20. ip[j]++
  21. if ip[j] > 0 {
  22. break
  23. }
  24. }
  25. }
  26. func isValidIPAddr(ipAddr string) bool {
  27. ip := net.ParseIP(ipAddr)
  28. if ip == nil {
  29. return false
  30. }
  31. return true
  32. }
  33. func ipWithinCIDR(ipAddr string, cidr string) bool {
  34. // Parse the CIDR string
  35. _, ipNet, err := net.ParseCIDR(cidr)
  36. if err != nil {
  37. return false
  38. }
  39. // Parse the IP address
  40. ip := net.ParseIP(ipAddr)
  41. if ip == nil {
  42. return false
  43. }
  44. // Check if the IP address is in the CIDR range
  45. return ipNet.Contains(ip)
  46. }