addr.go 1004 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package netlink
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. )
  7. // Addr represents an IP address from netlink. Netlink ip addresses
  8. // include a mask, so it stores the address as a net.IPNet.
  9. type Addr struct {
  10. *net.IPNet
  11. Label string
  12. Flags int
  13. Scope int
  14. }
  15. // String returns $ip/$netmask $label
  16. func (a Addr) String() string {
  17. return strings.TrimSpace(fmt.Sprintf("%s %s", a.IPNet, a.Label))
  18. }
  19. // ParseAddr parses the string representation of an address in the
  20. // form $ip/$netmask $label. The label portion is optional
  21. func ParseAddr(s string) (*Addr, error) {
  22. label := ""
  23. parts := strings.Split(s, " ")
  24. if len(parts) > 1 {
  25. s = parts[0]
  26. label = parts[1]
  27. }
  28. m, err := ParseIPNet(s)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return &Addr{IPNet: m, Label: label}, nil
  33. }
  34. // Equal returns true if both Addrs have the same net.IPNet value.
  35. func (a Addr) Equal(x Addr) bool {
  36. sizea, _ := a.Mask.Size()
  37. sizeb, _ := x.Mask.Size()
  38. // ignore label for comparison
  39. return a.IP.Equal(x.IP) && sizea == sizeb
  40. }