feat(arp): 自 go-hua 迁入 ARP 表查询与定时刷新缓存
- IP→MAC 查询(AutoRefresh 后台刷新/Search/Table), 新增依赖 mostlygeek/arp - 附测试、examples/arp 例程与包 README
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package arp
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// cache ARP 表缓存,读写加锁保证并发安全
|
||||
type cache struct {
|
||||
sync.RWMutex
|
||||
table ArpTable
|
||||
|
||||
Updated time.Time
|
||||
UpdatedCount int
|
||||
}
|
||||
|
||||
// Refresh 重新读取系统 ARP 表,并记录刷新时间与累计次数
|
||||
func (c *cache) Refresh() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
c.table = Table()
|
||||
c.Updated = time.Now()
|
||||
c.UpdatedCount += 1
|
||||
}
|
||||
|
||||
// Search 按 IP 查询 MAC 地址,缓存未命中时自动刷新一次后重查
|
||||
func (c *cache) Search(ip string) string {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
|
||||
mac, ok := c.table[ip]
|
||||
|
||||
if !ok {
|
||||
c.RUnlock()
|
||||
c.Refresh()
|
||||
c.RLock()
|
||||
mac = c.table[ip]
|
||||
}
|
||||
|
||||
return mac
|
||||
}
|
||||
Reference in New Issue
Block a user