netlink.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Package netlink provides a simple library for netlink. Netlink is
  2. // the interface a user-space program in linux uses to communicate with
  3. // the kernel. It can be used to add and remove interfaces, set up ip
  4. // addresses and routes, and confiugre ipsec. Netlink communication
  5. // requires elevated privileges, so in most cases this code needs to
  6. // be run as root. The low level primitives for netlink are contained
  7. // in the nl subpackage. This package attempts to provide a high-level
  8. // interface that is loosly modeled on the iproute2 cli.
  9. package netlink
  10. import (
  11. "net"
  12. "github.com/vishvananda/netlink/nl"
  13. )
  14. const (
  15. // Family type definitions
  16. FAMILY_ALL = nl.FAMILY_ALL
  17. FAMILY_V4 = nl.FAMILY_V4
  18. FAMILY_V6 = nl.FAMILY_V6
  19. )
  20. // ParseIPNet parses a string in ip/net format and returns a net.IPNet.
  21. // This is valuable because addresses in netlink are often IPNets and
  22. // ParseCIDR returns an IPNet with the IP part set to the base IP of the
  23. // range.
  24. func ParseIPNet(s string) (*net.IPNet, error) {
  25. ip, ipNet, err := net.ParseCIDR(s)
  26. if err != nil {
  27. return nil, err
  28. }
  29. return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
  30. }
  31. // NewIPNet generates an IPNet from an ip address using a netmask of 32 or 128.
  32. func NewIPNet(ip net.IP) *net.IPNet {
  33. if ip.To4() != nil {
  34. return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
  35. }
  36. return &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)}
  37. }