-
Notifications
You must be signed in to change notification settings - Fork 13
/
router_mgr.go
104 lines (81 loc) · 1.75 KB
/
router_mgr.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
package main
import (
"net"
"sort"
"sync"
)
type RouterMgr struct {
routetable map[string]string
nettable map[string]*net.IPNet
mutex *sync.RWMutex
sortedtable []string
}
func NewRouterMgr() *RouterMgr {
rm := &RouterMgr{
routetable: make(map[string]string),
mutex: &sync.RWMutex{},
sortedtable: make([]string, 0),
nettable: make(map[string]*net.IPNet),
}
return rm
}
func (rm *RouterMgr) AddRoute(cidr string, gw string) bool {
rm.mutex.Lock()
defer rm.mutex.Unlock()
_, ok := rm.routetable[cidr]
if ok {
return false
}
rm.routetable[cidr] = gw
var sortedtable []string
for route := range rm.routetable {
sortedtable = append(sortedtable, route)
_, subnet, err := net.ParseCIDR(route)
if err != nil {
continue
}
rm.nettable[route] = subnet
}
sort.Strings(sortedtable)
rm.sortedtable = sortedtable
return true
}
func (rm *RouterMgr) GetRoute(cidr string) string {
rm.mutex.RLock()
defer rm.mutex.RUnlock()
return rm.routetable[cidr]
}
func (rm *RouterMgr) DelRoute(cidr string) {
rm.mutex.Lock()
defer rm.mutex.Unlock()
delete(rm.routetable, cidr)
var sortedtable []string
for route := range rm.routetable {
sortedtable = append(sortedtable, route)
_, subnet, err := net.ParseCIDR(route)
if err != nil {
continue
}
rm.nettable[route] = subnet
}
sort.Strings(sortedtable)
rm.sortedtable = sortedtable
}
func (rm *RouterMgr) FindRoute(destIP net.IP) string {
rm.mutex.RLock()
defer rm.mutex.RUnlock()
slen := len(rm.sortedtable)
for i := slen - 1; i > -1; i-- {
route := rm.sortedtable[i]
subnet := rm.nettable[route]
if subnet == nil {
continue
}
gw := rm.routetable[route]
find := subnet.Contains(net.IP(destIP))
if find {
return gw
}
}
return ""
}