dockerfiles/anylink/server/pkg/arpdis/addr.go

102 lines
1.7 KiB
Go
Raw Normal View History

2021-06-08 20:45:26 +08:00
package arpdis
import (
"net"
"sync"
"time"
2021-08-26 23:09:52 +08:00
"github.com/bjdgyc/anylink/pkg/utils"
2021-06-08 20:45:26 +08:00
)
const (
StaleTimeNormal = time.Minute * 5
StaleTimeUnreachable = time.Minute * 10
TypeNormal = 0
TypeUnreachable = 1
TypeStatic = 2
)
var (
2021-08-26 23:09:52 +08:00
table = make(map[string]*Addr, 128)
2021-06-08 20:45:26 +08:00
tableMu sync.RWMutex
)
type Addr struct {
IP net.IP
HardwareAddr net.HardwareAddr
disTime time.Time
Type int8
}
func Lookup(ip net.IP, onlyTable bool) *Addr {
addr := tableLookup(ip.To4())
if addr != nil || onlyTable {
return addr
}
addr = doLookup(ip.To4())
Add(addr)
return addr
}
// Add adds a IP-MAC map to a runtime ARP table.
func tableLookup(ip net.IP) *Addr {
2021-08-26 23:09:52 +08:00
tableMu.RLock()
2021-06-08 20:45:26 +08:00
addr := table[ip.To4().String()]
2021-08-26 23:09:52 +08:00
tableMu.RUnlock()
2021-06-08 20:45:26 +08:00
if addr == nil {
return nil
}
// 判断老化过期时间
2021-08-26 23:09:52 +08:00
tSub := utils.NowSec().Sub(addr.disTime)
2021-06-08 20:45:26 +08:00
switch addr.Type {
2021-08-26 23:09:52 +08:00
case TypeStatic:
2021-06-08 20:45:26 +08:00
case TypeNormal:
2021-08-26 23:09:52 +08:00
if tSub > StaleTimeNormal {
2021-06-08 20:45:26 +08:00
return nil
}
case TypeUnreachable:
2021-08-26 23:09:52 +08:00
if tSub > StaleTimeUnreachable {
2021-06-08 20:45:26 +08:00
return nil
}
}
return addr
}
// Add adds a IP-MAC map to a runtime ARP table.
func Add(addr *Addr) {
if addr == nil {
return
}
if addr.disTime.IsZero() {
2021-08-26 23:09:52 +08:00
addr.disTime = utils.NowSec()
2021-06-08 20:45:26 +08:00
}
ip := addr.IP.To4().String()
tableMu.Lock()
defer tableMu.Unlock()
if a, ok := table[ip]; ok {
// 静态地址只能设置一次
if a.Type == TypeStatic {
return
}
}
table[ip] = addr
}
// Delete removes an IP from the runtime ARP table.
func Delete(ip net.IP) {
tableMu.Lock()
defer tableMu.Unlock()
delete(table, ip.To4().String())
}
// List returns the current runtime ARP table.
func List() map[string]*Addr {
tableMu.RLock()
defer tableMu.RUnlock()
return table
}