forked from jsimonetti/rtnetlink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_address_add_test.go
60 lines (51 loc) · 1.33 KB
/
example_address_add_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
//go:build linux
// +build linux
package rtnetlink_test
import (
"encoding/binary"
"log"
"net"
"github.com/jsimonetti/rtnetlink"
"golang.org/x/sys/unix"
)
// Add IP address '127.0.0.2/8' to an interface 'lo'
func Example_addAddress() {
// Gather the interface Index
iface, _ := net.InterfaceByName("lo")
// Get an ip address to add to the interface
addr, cidr, _ := net.ParseCIDR("127.0.0.2/8")
// Dial a connection to the rtnetlink socket
conn, err := rtnetlink.Dial(nil)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Test for the right address family for addr
family := unix.AF_INET6
to4 := cidr.IP.To4()
if to4 != nil {
family = unix.AF_INET
}
// Calculate the prefix length
ones, _ := cidr.Mask.Size()
// Calculate the broadcast IP
// Only used when family is AF_INET
var brd net.IP
if to4 != nil {
brd = make(net.IP, len(to4))
binary.BigEndian.PutUint32(brd, binary.BigEndian.Uint32(to4)|^binary.BigEndian.Uint32(net.IP(cidr.Mask).To4()))
}
// Send the message using the rtnetlink.Conn
err = conn.Address.New(&rtnetlink.AddressMessage{
Family: uint8(family),
PrefixLength: uint8(ones),
Scope: unix.RT_SCOPE_UNIVERSE,
Index: uint32(iface.Index),
Attributes: &rtnetlink.AddressAttributes{
Address: addr,
Local: addr,
Broadcast: brd,
},
})
log.Fatal(err)
}