compact_ips.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package netutils2
  15. import (
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. "yunion.io/x/pkg/errors"
  20. )
  21. func ExpandCompactIps(ipstr string) ([]string, error) {
  22. ips := make([]string, 0)
  23. ipSegs := strings.Split(strings.TrimSpace(ipstr), ";")
  24. for _, ipSeg := range ipSegs {
  25. parts := strings.Split(ipSeg, ".")
  26. if len(parts) <= 3 {
  27. return nil, errors.Wrap(errors.ErrInvalidFormat, ipSeg)
  28. }
  29. hosts := strings.Split(parts[3], ",")
  30. for _, host := range hosts {
  31. if strings.Index(host, "-") > 0 {
  32. subhosts := strings.Split(host, "-")
  33. if len(subhosts) != 2 {
  34. return nil, errors.Wrap(errors.ErrInvalidFormat, ipSeg)
  35. }
  36. start, err := strconv.Atoi(subhosts[0])
  37. if err != nil {
  38. return nil, errors.Wrap(errors.ErrInvalidFormat, ipSeg)
  39. }
  40. end, err := strconv.Atoi(subhosts[1])
  41. if err != nil {
  42. return nil, errors.Wrap(errors.ErrInvalidFormat, ipSeg)
  43. }
  44. for i := start; i <= end; i++ {
  45. ips = append(ips, fmt.Sprintf("%s.%s.%s.%d", parts[0], parts[1], parts[2], i))
  46. }
  47. } else {
  48. ips = append(ips, fmt.Sprintf("%s.%s.%s.%s", parts[0], parts[1], parts[2], host))
  49. }
  50. }
  51. }
  52. return ips, nil
  53. }