File: example_route_add_test.go

package info (click to toggle)
golang-github-jsimonetti-rtnetlink 2.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,264 kB
  • sloc: makefile: 2
file content (50 lines) | stat: -rw-r--r-- 956 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//go:build linux
// +build linux

package rtnetlink_test

import (
	"log"
	"net"

	"github.com/jsimonetti/rtnetlink/v2"
	"golang.org/x/sys/unix"
)

// Add a route
func Example_addRoute() {
	// Gather the interface Index
	iface, _ := net.InterfaceByName("lo")
	// Get a route to add
	_, dst, _ := net.ParseCIDR("192.168.0.0/16")
	// Get a gw to use
	gw := net.ParseIP("127.0.0.1")

	// Dial a connection to the rtnetlink socket
	conn, err := rtnetlink.Dial(nil)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	attr := rtnetlink.RouteAttributes{
		Dst:      dst.IP,
		OutIface: uint32(iface.Index),
	}
	if gw == nil {
		attr.Gateway = gw
	}
	ones, _ := dst.Mask.Size()

	err = conn.Route.Add(&rtnetlink.RouteMessage{
		Family:     unix.AF_INET,
		Table:      unix.RT_TABLE_MAIN,
		Protocol:   unix.RTPROT_BOOT,
		Scope:      unix.RT_SCOPE_LINK,
		Type:       unix.RTN_UNICAST,
		DstLength:  uint8(ones),
		Attributes: attr,
	})

	log.Fatal(err)
}