routeinfo.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. "net"
  18. "yunion.io/x/pkg/errors"
  19. )
  20. type SPrefixInfo struct {
  21. Prefix net.IP
  22. PrefixLen uint8
  23. }
  24. func (p SPrefixInfo) String() string {
  25. return fmt.Sprintf("%s/%d", p.Prefix.String(), p.PrefixLen)
  26. }
  27. type SRouteInfo struct {
  28. SPrefixInfo
  29. Gateway net.IP
  30. }
  31. func (r SRouteInfo) String() string {
  32. return fmt.Sprintf("%s via %s", r.SPrefixInfo.String(), r.Gateway.String())
  33. }
  34. func ParseRouteInfo(route []string) (*SRouteInfo, error) {
  35. if len(route) < 2 {
  36. return nil, errors.Wrapf(errors.ErrInvalidStatus, "invalid route %#v", route)
  37. }
  38. _, prefixLen, err := net.ParseCIDR(route[0])
  39. if err != nil {
  40. return nil, errors.Wrapf(err, "net.ParseCIDR %s", route[0])
  41. }
  42. ones, _ := prefixLen.Mask.Size()
  43. return &SRouteInfo{
  44. SPrefixInfo: SPrefixInfo{
  45. Prefix: prefixLen.IP,
  46. PrefixLen: uint8(ones),
  47. },
  48. Gateway: net.ParseIP(route[1]),
  49. }, nil
  50. }