diff --git a/main.go b/main.go index e6e595a..6a4c932 100644 --- a/main.go +++ b/main.go @@ -27,7 +27,8 @@ func main() { defer conn.Close() buff := make([]byte, 1024) - log.Println("waiting") + log.Println("Running") + routes.Timer() for { n, UDPAddr, err := conn.ReadFromUDP(buff) if err != nil { @@ -39,7 +40,7 @@ func main() { log.Fatalln(err) } routes.ParseRoutes(*UDPAddr, &rip.RIP) - for _, v := range routes { + for _, v := range routes.Routes { fmt.Printf("Route:%s\tSubnet:%s\tNexthop:%s\tMetric:%d\tTime: %v\n", v.Addr.String(), v.Subnet.String(), v.Nexthop.String(), v.Metric, v.TTL.Unix()) } fmt.Println("") diff --git a/ripv2/routes/routes.go b/ripv2/routes/routes.go index 0692c01..9ade96b 100644 --- a/ripv2/routes/routes.go +++ b/ripv2/routes/routes.go @@ -4,12 +4,16 @@ import ( "crypto/sha256" "fmt" "net" + "sync" "time" "github.com/crip/ripv2" ) -type Routes map[string]Route +type Routes struct { + Routes map[string]Route + sync.Mutex +} type Route struct { Addr net.IP @@ -19,9 +23,10 @@ type Route struct { TTL time.Time } -func New() Routes { - routes := make(map[string]Route, 25) - return routes +func New() *Routes { + var routes Routes + routes.Routes = make(map[string]Route, 25) + return &routes } func (r *Routes) append(route Route) { @@ -29,13 +34,15 @@ func (r *Routes) append(route Route) { h := sha256.New() h.Write([]byte(key)) bs := h.Sum(nil) - k, ok := (*r)[string(bs)] + r.Lock() + defer r.Unlock() + k, ok := r.Routes[string(bs)] if !ok { - (*r)[string(bs)] = route + r.Routes[string(bs)] = route return } k.TTL = time.Now() - (*r)[string(bs)] = k + r.Routes[string(bs)] = k } func (r *Routes) ParseRoutes(addr net.UDPAddr, rip *[25]ripv2.RIP) { diff --git a/ripv2/routes/timers.go b/ripv2/routes/timers.go new file mode 100644 index 0000000..d5c294d --- /dev/null +++ b/ripv2/routes/timers.go @@ -0,0 +1,23 @@ +package routes + +import ( + "time" +) + +func (r *Routes) Timer() { + t := time.NewTimer(time.Minute * 1) + go func() { + for { + <-t.C + r.Lock() + for k, route := range r.Routes { + if time.Since(route.TTL) >= time.Minute*2 { + delete(r.Routes, k) + continue + } + } + r.Unlock() + t.Reset(time.Minute * 1) + } + }() +}