addr.go 1.2 KB

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