-
Notifications
You must be signed in to change notification settings - Fork 97
/
example_test.go
110 lines (95 loc) · 2.5 KB
/
example_test.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package netlink_test
import (
"log"
"github.com/mdlayher/netlink"
"github.com/mdlayher/netlink/nlenc"
"github.com/mdlayher/netlink/nltest"
)
// This example demonstrates using a netlink.Conn to execute requests against
// netlink.
func ExampleConn_execute() {
// Speak to generic netlink using netlink
const familyGeneric = 16
c, err := netlink.Dial(familyGeneric, nil)
if err != nil {
log.Fatalf("failed to dial netlink: %v", err)
}
defer c.Close()
// Ask netlink to send us an acknowledgement, which will contain
// a copy of the header we sent to it
req := netlink.Message{
Header: netlink.Header{
// Package netlink will automatically set header fields
// which are set to zero
Flags: netlink.Request | netlink.Acknowledge,
},
}
// Perform a request, receive replies, and validate the replies
msgs, err := c.Execute(req)
if err != nil {
log.Fatalf("failed to execute request: %v", err)
}
if c := len(msgs); c != 1 {
log.Fatalf("expected 1 message, but got: %d", c)
}
// Decode the copied request header, starting after 4 bytes
// indicating "success"
var res netlink.Message
if err := (&res).UnmarshalBinary(msgs[0].Data[4:]); err != nil {
log.Fatalf("failed to unmarshal response: %v", err)
}
log.Printf("res: %+v", res)
}
// This example demonstrates using a netlink.Conn to listen for multicast group
// messages generated by the addition and deletion of network interfaces.
func ExampleConn_listenMulticast() {
const (
// Speak to route netlink using netlink
familyRoute = 0
// Listen for events triggered by addition or deletion of
// network interfaces
rtmGroupLink = 0x1
)
c, err := netlink.Dial(familyRoute, &netlink.Config{
// Groups is a bitmask; more than one group can be specified
// by OR'ing multiple group values together
Groups: rtmGroupLink,
})
if err != nil {
log.Fatalf("failed to dial netlink: %v", err)
}
defer c.Close()
for {
// Listen for netlink messages triggered by multicast groups
msgs, err := c.Receive()
if err != nil {
log.Fatalf("failed to receive messages: %v", err)
}
log.Printf("msgs: %+v", msgs)
}
}
func exampleAttributes() []byte {
return nltest.MustMarshalAttributes([]netlink.Attribute{
{
Type: 1,
Data: nlenc.Uint16Bytes(1),
},
{
Type: 2,
Data: nlenc.Bytes("hello world"),
},
{
Type: 3,
Data: nltest.MustMarshalAttributes([]netlink.Attribute{
{
Type: 1,
Data: nlenc.Uint32Bytes(2),
},
{
Type: 2,
Data: nlenc.Uint32Bytes(3),
},
}),
},
})
}