Checkpoint

This commit is contained in:
2025-10-01 15:37:55 +02:00
parent 4a60059ff2
commit 03352e3312
31 changed files with 2611 additions and 384 deletions

View File

@@ -0,0 +1,63 @@
package arp
import (
"net"
"sync"
"time"
"github.com/sirupsen/logrus"
)
func init() {
go func() {
t := time.NewTicker(time.Second * 5)
for {
refresh()
<-t.C
}
}()
}
var table sync.Map
func refresh() {
t, err := lookup()
if err != nil {
logrus.StandardLogger().WithError(err).Warn("arp cache refresh failed")
} else {
for k, v := range t {
logrus.StandardLogger().WithFields(logrus.Fields{
"mac": v,
"ip": k,
}).Debug("Updating ARP cache")
table.Store(k, v)
}
}
}
func Get(addr net.Addr) net.HardwareAddr {
if addr == nil {
logrus.StandardLogger().Trace("No address found, can't lookup IP for MAC")
return nil
}
var ip net.IP
switch addr := addr.(type) {
case *net.TCPAddr:
ip = addr.IP
case *net.UDPAddr:
ip = addr.IP
}
if ip == nil {
logrus.StandardLogger().WithField("addr", addr.String()).Trace("No IP address found, can't lookup MAC")
return nil
}
if v, ok := table.Load(ip.String()); ok {
logrus.StandardLogger().WithField("ip", ip.String()).Tracef("%s is at %s", ip, v.(net.HardwareAddr).String())
return v.(net.HardwareAddr)
}
logrus.StandardLogger().WithField("ip", ip.String()).Trace("No MAC address found")
return nil
}

View File

@@ -0,0 +1,32 @@
package arp
import (
"bufio"
"net"
"os"
"strings"
)
func lookup() (map[string]net.HardwareAddr, error) {
f, err := os.Open("/proc/net/arp")
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
t := make(map[string]net.HardwareAddr)
s := bufio.NewScanner(f)
for i := 0; s.Scan(); i++ {
if i == 0 {
continue
}
line := strings.Fields(s.Text())
if len(line) < 4 {
continue
}
if mac, err := net.ParseMAC(line[3]); err == nil {
t[line[0]] = mac
}
}
return t, nil
}

View File

@@ -0,0 +1,37 @@
//go:build !linux
// +build !linux
// ^ Linux isn't Unix anyway :P
package arp
import (
"net"
"os/exec"
"strings"
)
func lookup() (map[string]net.HardwareAddr, error) {
data, err := exec.Command("arp", "-an").Output()
if err != nil {
return nil, err
}
t := make(map[string]net.HardwareAddr)
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) < 3 {
continue
}
// strip brackets around IP
ip := strings.ReplaceAll(fields[1], "(", "")
ip = strings.ReplaceAll(ip, ")", "")
if mac, err := net.ParseMAC(fields[3]); err == nil {
t[ip] = mac
}
}
return t, nil
}