Debian Codegraph @

network/arp.go

raw symbols SCIP
1 package network
2
3 import (
4 "fmt"
5 "strings"
6 "sync"
7
8 "github.com/bettercap/bettercap/core"
9 )
10
11 type ArpTable map[string]string
12
13 var (
14 arpWasParsed = false
15 arpLock = &sync.RWMutex{}
16 arpTable = make(ArpTable)
17 )
18
19 func ArpUpdate(iface string) (ArpTable, error) {
20 arpLock.Lock()
21 defer arpLock.Unlock()
22
23 // Signal we parsed the ARP table at least once.
24 arpWasParsed = true
25
26 // Run "arp -an" (darwin) or "ip neigh" (linux) and parse the output
27 output, err := core.Exec(ArpCmd, ArpCmdOpts)
28 if err != nil {
29 return arpTable, err
30 }
31
32 newTable := make(ArpTable)
33 for _, line := range strings.Split(output, "\n") {
34 m := ArpTableParser.FindStringSubmatch(line)
35 if len(m) == ArpTableTokens {
36 ipIndex := ArpTableTokenIndex[0]
37 hwIndex := ArpTableTokenIndex[1]
38 ifIndex := ArpTableTokenIndex[2]
39
40 address := m[ipIndex]
41 mac := m[hwIndex]
42 ifname := iface
43
44 if ifIndex != -1 {
45 ifname = m[ifIndex]
46 }
47
48 if ifname == iface {
49 newTable[address] = mac
50 }
51 }
52 }
53
54 arpTable = newTable
55
56 return arpTable, nil
57 }
58
59 func ArpLookup(iface string, address string, refresh bool) (string, error) {
60 // Refresh ARP table if first run or if a force refresh has been instructed.
61 if !ArpParsed() || refresh {
62 if _, err := ArpUpdate(iface); err != nil {
63 return "", err
64 }
65 }
66
67 arpLock.RLock()
68 defer arpLock.RUnlock()
69
70 // Lookup the hardware address of this ip.
71 if mac, found := arpTable[address]; found {
72 return mac, nil
73 }
74
75 return "", fmt.Errorf("Could not find mac for %s", address)
76 }
77
78 func ArpInverseLookup(iface string, mac string, refresh bool) (string, error) {
79 if !ArpParsed() || refresh {
80 if _, err := ArpUpdate(iface); err != nil {
81 return "", err
82 }
83 }
84
85 arpLock.RLock()
86 defer arpLock.RUnlock()
87
88 for ip, hw := range arpTable {
89 if hw == mac {
90 return ip, nil
91 }
92 }
93
94 return "", fmt.Errorf("Could not find IP for %s", mac)
95 }
96
97 func ArpParsed() bool {
98 arpLock.RLock()
99 defer arpLock.RUnlock()
100 return arpWasParsed
101 }