Files

72 lines
1.5 KiB
Go

//go:build linux
package scanner
import (
"bufio"
"encoding/binary"
"net"
"net/netip"
"os"
"strconv"
"strings"
)
// readARPTable returns the complete entries of the kernel's ARP cache.
func readARPTable() (map[netip.Addr]net.HardwareAddr, error) {
f, err := os.Open("/proc/net/arp")
if err != nil {
return nil, err
}
defer f.Close()
table := make(map[netip.Addr]net.HardwareAddr)
sc := bufio.NewScanner(f)
sc.Scan() // header
for sc.Scan() {
fields := strings.Fields(sc.Text())
if len(fields) < 4 {
continue
}
flags, _ := strconv.ParseUint(strings.TrimPrefix(fields[2], "0x"), 16, 32)
if flags&0x2 == 0 { // ATF_COM: entry is complete
continue
}
ip, err := netip.ParseAddr(fields[0])
if err != nil {
continue
}
if mac, err := net.ParseMAC(fields[3]); err == nil && validMAC(mac) {
table[ip] = mac
}
}
return table, sc.Err()
}
// defaultGateway returns the IPv4 default gateway reached via iface.
func defaultGateway(iface *net.Interface) netip.Addr {
f, err := os.Open("/proc/net/route")
if err != nil {
return netip.Addr{}
}
defer f.Close()
sc := bufio.NewScanner(f)
sc.Scan() // header
for sc.Scan() {
fields := strings.Fields(sc.Text())
if len(fields) < 3 || fields[1] != "00000000" {
continue
}
if iface != nil && fields[0] != iface.Name {
continue
}
v, err := strconv.ParseUint(fields[2], 16, 32)
if err != nil || v == 0 {
continue
}
var b [4]byte
binary.LittleEndian.PutUint32(b[:], uint32(v))
return netip.AddrFrom4(b)
}
return netip.Addr{}
}