vishvananda / netlink

Simple netlink library for go.
Apache License 2.0
2.85k stars 744 forks source link

mpls route via inet #500

Open dontcare opened 4 years ago

dontcare commented 4 years ago

Hi, for 'ip -f mpls route add 100 dev lo' i do this:

loLink,_ := nlHndl.LinkByName("lo")
mplsDst := 100
route := netlink.Route{
  MPLSDst: &mplsDst,
  LinkIndex:loLink.Attrs().Index,
}
nlHndl.RouteAdd(&route)

ip -f mpls route add 100 via inet 127.0.0.1 how to do similar with this library?

ljluestc commented 1 year ago

package main

import ( "fmt" "net" "os"

"github.com/vishvananda/netlink"

)

func main() { nlHndl, err := netlink.NewHandle() if err != nil { fmt.Printf("Failed to create netlink handle: %v\n", err) os.Exit(1) } defer nlHndl.Delete()

loLink, err := nlHndl.LinkByName("lo")
if err != nil {
    fmt.Printf("Failed to get lo link: %v\n", err)
    os.Exit(1)
}

mplsDst := 100
route := netlink.Route{
    Dst:      &net.IPNet{},
    MPLSDst:  &mplsDst,
    LinkIndex: loLink.Attrs().Index,
}

if err := nlHndl.RouteAdd(&route); err != nil {
    fmt.Printf("Failed to add MPLS route: %v\n", err)
    os.Exit(1)
}

nextHopIP := net.ParseIP("127.0.0.1")
routeVia := netlink.Route{
    Dst:       &net.IPNet{IP: nextHopIP, Mask: net.CIDRMask(32, 32)},
    MPLSDst:   &mplsDst,
    LinkIndex: loLink.Attrs().Index,
}

if err := nlHndl.RouteAdd(&routeVia); err != nil {
    fmt.Printf("Failed to add MPLS route with via: %v\n", err)
    os.Exit(1)
}

fmt.Println("MPLS route added successfully")

}