Brijesh's Git Server — network-scan @ e6d5a05b95b3a6a42e789e60e798021569e2bd3c

arp/arp.go (view raw)

 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
package arp

import (
	"fmt"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

type Device struct {
	IP  string
	MAC string
}

func GetDevices() ([]Device, error) {
	if runtime.GOOS == "windows" {
		return nil, fmt.Errorf("this program is not supported on Windows")
	}

	cmd := exec.Command("arp", "-a")
	output, err := cmd.Output()
	if err != nil {
		return nil, err
	}

	return parseARPTable(string(output)), nil
}

func parseARPTable(arpTable string) []Device {
	var devices []Device

	pattern := regexp.MustCompile(`(\d+\.\d+\.\d+\.\d+).*?(\S+:\S+:\S+:\S+:\S+:\S+)`)

	lines := strings.Split(arpTable, "\n")
	for _, line := range lines {
		matches := pattern.FindStringSubmatch(line)
		if len(matches) == 3 {
			device := Device{
				IP:  matches[1],
				MAC: matches[2],
			}
			devices = append(devices, device)
		}
	}

	return devices
}