-
Notifications
You must be signed in to change notification settings - Fork 24
/
ipv6zone.go
73 lines (66 loc) · 1.28 KB
/
ipv6zone.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
// Copyright 2016 Mikio Hara. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tcp
import (
"fmt"
"net"
"strconv"
"sync"
"time"
)
type ipv6ZoneCache struct {
sync.RWMutex
lastFetched time.Time
toIndex map[string]int
toName map[int]string
}
var zoneCache = ipv6ZoneCache{
toIndex: make(map[string]int),
toName: make(map[int]string),
}
func (zc *ipv6ZoneCache) index(name string) int {
if name == "" {
return 0
}
zc.update()
zc.RLock()
defer zc.RUnlock()
index, ok := zc.toIndex[name]
if !ok {
index, _ = strconv.Atoi(name)
}
return index
}
func (zc *ipv6ZoneCache) name(index int) string {
if index == 0 {
return ""
}
zc.update()
zc.RLock()
defer zc.RUnlock()
name, ok := zc.toName[index]
if !ok {
name = fmt.Sprintf("%d", index)
}
return name
}
func (zc *ipv6ZoneCache) update() {
zc.Lock()
defer zc.Unlock()
now := time.Now()
if zc.lastFetched.After(now.Add(-60 * time.Second)) {
return
}
zc.lastFetched = now
ift, err := net.Interfaces()
if err != nil {
return
}
zc.toIndex = make(map[string]int, len(ift))
zc.toName = make(map[int]string, len(ift))
for _, ifi := range ift {
zc.toIndex[ifi.Name] = ifi.Index
zc.toName[ifi.Index] = ifi.Name
}
}