addr.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. Peer *net.IPNet
  15. Broadcast net.IP
  16. PreferedLft int
  17. ValidLft int
  18. }
  19. // String returns $ip/$netmask $label
  20. func (a Addr) String() string {
  21. return strings.TrimSpace(fmt.Sprintf("%s %s", a.IPNet, a.Label))
  22. }
  23. // ParseAddr parses the string representation of an address in the
  24. // form $ip/$netmask $label. The label portion is optional
  25. func ParseAddr(s string) (*Addr, error) {
  26. label := ""
  27. parts := strings.Split(s, " ")
  28. if len(parts) > 1 {
  29. s = parts[0]
  30. label = parts[1]
  31. }
  32. m, err := ParseIPNet(s)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &Addr{IPNet: m, Label: label}, nil
  37. }
  38. // Equal returns true if both Addrs have the same net.IPNet value.
  39. func (a Addr) Equal(x Addr) bool {
  40. sizea, _ := a.Mask.Size()
  41. sizeb, _ := x.Mask.Size()
  42. // ignore label for comparison
  43. return a.IP.Equal(x.IP) && sizea == sizeb
  44. }
  45. func (a Addr) PeerEqual(x Addr) bool {
  46. sizea, _ := a.Peer.Mask.Size()
  47. sizeb, _ := x.Peer.Mask.Size()
  48. // ignore label for comparison
  49. return a.Peer.IP.Equal(x.Peer.IP) && sizea == sizeb
  50. }