-
Notifications
You must be signed in to change notification settings - Fork 35
/
arp_linux.go
57 lines (44 loc) · 1.1 KB
/
arp_linux.go
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
// +build linux
package arp
import (
"errors"
"fmt"
"net"
"os/exec"
"regexp"
)
var lineMatch = regexp.MustCompile(`([0-9\.]+)\s+dev\s+([^\s]+)\s+lladdr\s+([0-9a-f:]+)`)
func doARPLookup(ip string) (*Address, error) {
ping := exec.Command("ping", "-c1", "-t1", ip)
if err := ping.Start(); err != nil {
return nil, err
}
if err := ping.Wait(); err != nil {
return nil, err
}
cmd := exec.Command("ip", "n", "show", ip)
out, err := cmd.Output()
if err != nil {
return nil, errors.New("No entry")
}
matches := lineMatch.FindAllStringSubmatch(string(out), 1)
if len(matches) > 0 && len(matches[0]) > 3 {
ipAddr := net.ParseIP(matches[0][1])
macAddrString := matches[0][3]
macAddr, err := net.ParseMAC(macAddrString)
if err != nil {
return nil, fmt.Errorf("ParseMAC: %v", err)
}
iface, err := net.InterfaceByName(matches[0][2])
if err != nil {
return nil, fmt.Errorf("InterfaceByName: %v", err)
}
localAddr := Address{
IP: ipAddr,
HardwareAddr: macAddr,
Interface: *iface,
}
return &localAddr, nil
}
return nil, errors.New("Lookup failed.")
}