arp_freebsd.go 1.1 KB

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