Merge pull request #92 from pmazzini/route

[rtnl] add RouteGet method
This commit is contained in:
Jeroen Simonetti 2020-11-10 09:07:08 +01:00 committed by GitHub
commit d2c240429e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 77 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package rtnl
import (
"errors"
"net"
"github.com/jsimonetti/rtnetlink/internal/unix"
@ -8,6 +9,12 @@ import (
"github.com/jsimonetti/rtnetlink"
)
// Route represents a route table entry
type Route struct {
Gateway net.IP
Interface *net.Interface
}
// generating route message
func genRouteMessage(ifc *net.Interface, dst net.IPNet, gw net.IP, options ...RouteOption) (rm *rtnetlink.RouteMessage, err error) {
@ -93,3 +100,35 @@ func (c *Conn) RouteDel(ifc *net.Interface, dst net.IPNet) error {
}
return c.Conn.Route.Delete(tx)
}
// RouteGet gets a single route to the given destination address.
func (c *Conn) RouteGet(dst net.IP) (*Route, error) {
af, err := addrFamily(dst)
if err != nil {
return nil, err
}
attr := rtnetlink.RouteAttributes{
Dst: dst,
}
tx := &rtnetlink.RouteMessage{
Family: uint8(af),
Table: unix.RT_TABLE_MAIN,
Attributes: attr,
}
rx, err := c.Conn.Route.Get(tx)
if err != nil {
return nil, err
}
if len(rx) == 0 {
return nil, errors.New("route wrong length")
}
ifindex := int(rx[0].Attributes.OutIface)
iface, err := c.LinkByIndex(ifindex)
if err != nil {
return nil, err
}
return &Route{
Gateway: rx[0].Attributes.Gateway,
Interface: iface,
}, nil
}

38
rtnl/route_live_test.go Normal file
View File

@ -0,0 +1,38 @@
// +build integration
package rtnl
import (
"net"
"testing"
)
func TestLiveRoute(t *testing.T) {
c, err := Dial(nil)
if err != nil {
t.Fatal(err)
}
defer c.Close()
route, err := c.RouteGet(net.ParseIP("8.8.8.8"))
if err != nil {
t.Fatal(err)
}
t.Logf("got route: %v", route)
if route.Gateway.IsUnspecified() {
t.Error("zero route.Gateway, expected non-zero")
}
if route.Gateway.IsLoopback() {
t.Error("lo route.Gatway, expected non lo")
}
if route.Interface == nil {
t.Error("nil route.Interface, expected non-nil")
}
if len(route.Interface.Name) == 0 {
t.Error("zero-length route.Interface.Name")
}
if hardwareAddrIsUnspecified(route.Interface.HardwareAddr) {
t.Error("zero route.Interface.HardwareAddr, expected non-zero")
}
}