arp_freebsd.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package neighbors
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os/exec"
  7. "goa.design/clue/log"
  8. )
  9. const (
  10. arpCmd = "arp"
  11. arpOutputVersion = "1"
  12. )
  13. type (
  14. arpOutput struct {
  15. Version string `json:"__version"`
  16. ARP struct {
  17. Cache []arpEntry `json:"arp-cache"`
  18. } `json:"arp"`
  19. }
  20. arpEntry struct {
  21. IPAddress string `json:"ip-address"`
  22. MACAddress string `json:"mac-address"`
  23. Interface string `json:"interface"`
  24. }
  25. )
  26. func (a *arp) entries(ctx context.Context, ifs Interfaces) (entries []arpEntry, err error) {
  27. cmd := exec.CommandContext(ctx, a.cmd, "--libxo=json", "-an")
  28. if len(ifs) == 1 {
  29. for ifi := range ifs {
  30. cmd.Args = append(cmd.Args, "-i", ifi)
  31. }
  32. }
  33. log.Debug(ctx, log.KV{K: "cmd", V: cmd})
  34. b, err := cmd.Output()
  35. if err != nil {
  36. return
  37. }
  38. o := &arpOutput{}
  39. if err = json.Unmarshal(b, o); err != nil {
  40. return
  41. }
  42. if o.Version != arpOutputVersion {
  43. err = fmt.Errorf("arp output version mismatch (got %v, expected %v)", o.Version, arpOutputVersion)
  44. return
  45. }
  46. entries = make([]arpEntry, 0, len(o.ARP.Cache))
  47. for _, e := range o.ARP.Cache {
  48. if e.IPAddress != "" {
  49. entries = append(entries, e)
  50. }
  51. }
  52. return
  53. }