summaryrefslogtreecommitdiff
path: root/adapters/arp/arp.go
blob: 19d76328144cc772213824d2b6d58dd00f1ef9e3 (plain) (blame)
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
package arp

import (
	"os/exec"
	"regexp"
	"strings"

	"penguins.lan/utils"
)

type ArpTable struct {
	AddrToMac map[utils.INet4]utils.Mac
}

// Lookup returns the canonical MAC for an IPv4 string, false if it isn't in the
// table or isn't parseable IPv4 (e.g. an IPv6 peer).
func (t *ArpTable) Lookup(ip string) (string, bool) {
	addr, err := utils.ParseINet4(ip)
	if err != nil {
		return "", false
	}
	mac, ok := t.AddrToMac[*addr]
	if !ok {
		return "", false
	}
	return mac.Format(), true
}

type TableProvider interface {
	Fetch() (*ArpTable, error)
}

var arpLine = regexp.MustCompile(`\((\d{1,3}(?:\.\d{1,3}){3})\) at ([0-9a-fA-F]{1,2}(?::[0-9a-fA-F]{1,2}){5})`)

type SystemProvider struct{}

func (SystemProvider) Fetch() (*ArpTable, error) {
	out, err := exec.Command("arp", "-an").Output()
	if err != nil {
		return nil, err
	}
	return parseTable(string(out)), nil
}

func parseTable(out string) *ArpTable {
	table := &ArpTable{AddrToMac: make(map[utils.INet4]utils.Mac)}
	for _, line := range strings.Split(out, "\n") {
		m := arpLine.FindStringSubmatch(line)
		if m == nil {
			continue
		}
		addr, err := utils.ParseINet4(m[1])
		if err != nil {
			continue
		}
		mac, err := utils.ParseMac(m[2])
		if err != nil {
			continue
		}
		table.AddrToMac[*addr] = *mac
	}
	return table
}