-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (79 loc) · 2.15 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"github.com/vishvananda/netlink"
)
func main() {
fmt.Printf("Dummy-int-init\n")
fmt.Printf("Contact: [email protected]\n")
fmt.Printf("Project: https://github.com/ccleouf66/dummy-net-init\n")
fmt.Printf("---\n\n")
if len(os.Args) != 3 {
log.Fatalf("Bad arguments number. \nUsage:\n %s interface-names interface-ip", os.Args[0])
}
var intName string = os.Args[1]
var intAddr string = os.Args[2]
// Check if the dummy link already exist
nl, err := netlink.LinkList()
if err != nil {
log.Fatalf("Error getting link list: %s\n", err)
}
for _, l := range nl {
if l.Type() == "dummy" {
if l.Attrs().Name == intName {
// Get link addresses
laddr, err := netlink.AddrList(l, 0)
if err != nil {
log.Fatalf("Error getting addresses for link %s: %s\n", l.Attrs().Name, err)
}
// Check all addresses
for _, addr := range laddr {
a, err := netlink.ParseAddr(intAddr)
if err != nil {
log.Fatalf("Error parsing addresses %s: \n%s\n", intAddr, err)
}
if addr.IPNet.IP.To4().Equal(a.IP) {
log.Printf("Interface %s with address %s already exist.\n", intName, intAddr)
return
}
}
// Interface exist, add new address
err = AddDummyAddr(intAddr, l.(*netlink.Dummy))
if err != nil {
log.Fatalf("%v\n", err)
}
return
}
}
}
// Configure new dummy interface
la := netlink.NewLinkAttrs()
la.Name = intName
dummyInt := &netlink.Dummy{LinkAttrs: la}
// Create dummy interface
err = netlink.LinkAdd(dummyInt)
if err != nil {
log.Fatalf("Could not create %s interface, are you priviliged ?:\n%v\n", la.Name, err)
}
// Add address to dummy interface
err = AddDummyAddr(intAddr, dummyInt)
if err != nil {
log.Fatalf("%v\n", err)
}
}
// AddDummyAddr add addr to dummy interface
func AddDummyAddr(addr string, dummy *netlink.Dummy) (err error) {
a, err := netlink.ParseAddr(addr)
if err != nil {
log.Printf("Could not create addr %s\n", addr)
return err
}
err = netlink.AddrAdd(dummy, a)
if err != nil {
log.Printf("Could not add address %s to interface %s\n", addr, dummy.Attrs().Name)
return err
}
return nil
}