diff --git a/README.md b/README.md index 09d88b6..0a2a832 100644 --- a/README.md +++ b/README.md @@ -62,9 +62,16 @@ sudo mac2ip dd:ee # Matches aa:bb:cc:dd:ee:ff sudo mac2ip 00:1a:2b # Find by vendor prefix ``` -**Specify interface:** +**List available interfaces:** +```bash +mac2ip --list +``` + +**Specify interface** (by name, index from `--list`, or description substring): ```bash sudo mac2ip -i eth0 aa:bb:cc:dd:ee:ff +sudo mac2ip -i 2 aa:bb:cc:dd:ee:ff # by index +sudo mac2ip -i "Ethernet" aa:bb:cc:dd:ee:ff # by description (handy on Windows) ``` **Help:** @@ -101,6 +108,22 @@ Windows typically **requires Administrator privileges** for packet capture. .\mac2ip.exe aa:bb:cc:dd:ee:ff ``` +**Choosing the right adapter on Windows** + +On Windows, Npcap reports interfaces as opaque device paths like +`\Device\NPF_{GUID}` rather than friendly names. Use `--list` to see all +adapters with their descriptions and IP addresses, then select one by index or +by a part of its description: + +```cmd +.\mac2ip.exe --list +.\mac2ip.exe -i 2 aa:bb:cc:dd:ee:ff +.\mac2ip.exe -i "Ethernet" aa:bb:cc:dd:ee:ff +``` + +Auto-detection (no `-i`) skips loopback and virtual/APIPA adapters and prefers +the interface with a real IPv4 address. + **Optional: Non-Admin Access (Advanced)** You can configure Npcap to allow non-admin users: diff --git a/README_DE.md b/README_DE.md index 527eafa..a2246a6 100644 --- a/README_DE.md +++ b/README_DE.md @@ -62,9 +62,16 @@ sudo mac2ip dd:ee # Matched aa:bb:cc:dd:ee:ff sudo mac2ip 00:1a:2b # Suche nach Hersteller-Prefix ``` -**Interface angeben:** +**Verfügbare Interfaces auflisten:** +```bash +mac2ip --list +``` + +**Interface angeben** (per Name, Index aus `--list` oder Teil der Beschreibung): ```bash sudo mac2ip -i eth0 aa:bb:cc:dd:ee:ff +sudo mac2ip -i 2 aa:bb:cc:dd:ee:ff # per Index +sudo mac2ip -i "Ethernet" aa:bb:cc:dd:ee:ff # per Beschreibung (praktisch unter Windows) ``` **Hilfe:** @@ -101,6 +108,22 @@ Windows benötigt typischerweise **Administrator-Rechte** für Packet Capture. .\mac2ip.exe aa:bb:cc:dd:ee:ff ``` +**Den richtigen Adapter unter Windows wählen** + +Unter Windows meldet Npcap Interfaces als kryptische Gerätepfade wie +`\Device\NPF_{GUID}` statt lesbarer Namen. Mit `--list` siehst du alle Adapter +mit Beschreibung und IP-Adressen und kannst dann per Index oder per Teil der +Beschreibung auswählen: + +```cmd +.\mac2ip.exe --list +.\mac2ip.exe -i 2 aa:bb:cc:dd:ee:ff +.\mac2ip.exe -i "Ethernet" aa:bb:cc:dd:ee:ff +``` + +Die Auto-Erkennung (ohne `-i`) überspringt Loopback- und virtuelle/APIPA-Adapter +und bevorzugt das Interface mit einer echten IPv4-Adresse. + **Optional: Ohne Admin-Rechte (Fortgeschritten)** Du kannst Npcap so konfigurieren, dass normale User es nutzen können: diff --git a/main.go b/main.go index 096c4b0..6018c42 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "os" + "strconv" "strings" "time" @@ -12,6 +13,10 @@ import ( "github.com/google/gopacket/pcap" ) +// pcapIfLoopback mirrors libpcap's PCAP_IF_LOOPBACK flag. gopacket exposes the +// raw Flags value but not the constant, so we define it here. +const pcapIfLoopback = 0x00000001 + func printHelp() { fmt.Println(`NAME mac2ip - live ARP traffic sniffer for MAC address lookup @@ -27,7 +32,10 @@ DESCRIPTION OPTIONS -h, --help Show this help message + -l, --list List available network interfaces and exit -i INTERFACE Specify network interface (default: auto-detect) + Accepts an interface name, a description substring + (useful on Windows), or an index from --list ARGUMENTS MAC_ADDRESS MAC address or pattern to monitor (optional) @@ -51,6 +59,13 @@ EXAMPLES Specify interface: sudo mac2ip -i eth0 aa:bb:cc:dd:ee:ff + List interfaces (helpful on Windows to find the right adapter): + mac2ip --list + + Select an interface by index or description (Windows): + mac2ip -i 2 aa:bb:cc:dd:ee:ff + mac2ip -i "Ethernet" aa:bb:cc:dd:ee:ff + Works even if device has wrong IP config (Layer 2): sudo mac2ip 00:11:22:33:44:55 @@ -75,9 +90,139 @@ func formatIP(addr []byte) string { return fmt.Sprintf("%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]) } +// isLoopback reports whether a device is a loopback interface. Windows does not +// name its loopback "lo", so we also check the pcap flag and the description. +func isLoopback(device pcap.Interface) bool { + if device.Name == "lo" { + return true + } + if device.Flags&pcapIfLoopback != 0 { + return true + } + return strings.Contains(strings.ToLower(device.Description), "loopback") +} + +// hasRoutableIPv4 reports whether a device has a "real" IPv4 address, i.e. not +// loopback and not link-local (169.254.x.x / APIPA). Such interfaces are the +// ones actually carrying LAN traffic and make the best auto-detect candidates. +func hasRoutableIPv4(device pcap.Interface) bool { + for _, a := range device.Addresses { + ip := a.IP.To4() + if ip == nil { + continue + } + if ip.IsLoopback() || ip.IsLinkLocalUnicast() { + continue + } + return true + } + return false +} + +// ipv4Strings returns the IPv4 addresses of a device as printable strings. +func ipv4Strings(device pcap.Interface) []string { + var ips []string + for _, a := range device.Addresses { + if ip := a.IP.To4(); ip != nil { + ips = append(ips, ip.String()) + } + } + return ips +} + +// listInterfaces prints all available capture interfaces with an index, name, +// description and IPv4 addresses. On Windows the name is an opaque +// \Device\NPF_{GUID} path, so the description and index are what users need. +func listInterfaces(devices []pcap.Interface) { + fmt.Println("Available network interfaces:") + fmt.Println() + for i, device := range devices { + fmt.Printf(" [%d] %s\n", i+1, device.Name) + if device.Description != "" { + fmt.Printf(" Description: %s\n", device.Description) + } + if ips := ipv4Strings(device); len(ips) > 0 { + fmt.Printf(" IPv4: %s\n", strings.Join(ips, ", ")) + } + if isLoopback(device) { + fmt.Printf(" (loopback)\n") + } + fmt.Println() + } + fmt.Println("Select one with: mac2ip -i ") +} + +// resolveInterface maps a user-supplied -i value to a concrete device name. +// It accepts, in order of precedence: an exact interface name, a 1-based index +// from --list, or a case-insensitive substring of the name or description +// (which is how users pick adapters on Windows). Returns an error describing +// the problem, including ambiguous matches. +func resolveInterface(devices []pcap.Interface, spec string) (string, error) { + // 1) Exact name match. + for _, device := range devices { + if device.Name == spec { + return device.Name, nil + } + } + + // 2) Numeric index (1-based, as shown by --list). + if idx, err := strconv.Atoi(spec); err == nil { + if idx < 1 || idx > len(devices) { + return "", fmt.Errorf("interface index %d out of range (have %d interfaces, use --list)", idx, len(devices)) + } + return devices[idx-1].Name, nil + } + + // 3) Case-insensitive substring of name or description. + needle := strings.ToLower(spec) + var matches []pcap.Interface + for _, device := range devices { + if strings.Contains(strings.ToLower(device.Name), needle) || + strings.Contains(strings.ToLower(device.Description), needle) { + matches = append(matches, device) + } + } + switch len(matches) { + case 0: + return "", fmt.Errorf("no interface matches %q (use --list to see available interfaces)", spec) + case 1: + return matches[0].Name, nil + default: + var b strings.Builder + fmt.Fprintf(&b, "%q matches multiple interfaces:\n", spec) + for _, m := range matches { + fmt.Fprintf(&b, " - %s", m.Name) + if m.Description != "" { + fmt.Fprintf(&b, " (%s)", m.Description) + } + b.WriteString("\n") + } + b.WriteString("Be more specific or use --list to pick by index") + return "", fmt.Errorf("%s", b.String()) + } +} + +// autoSelectInterface picks a sensible default capture interface: the first +// non-loopback device that has a routable IPv4 address, falling back to the +// first non-loopback device with any address, then to the first device. +func autoSelectInterface(devices []pcap.Interface) string { + for _, device := range devices { + if !isLoopback(device) && hasRoutableIPv4(device) { + return device.Name + } + } + for _, device := range devices { + if !isLoopback(device) && len(device.Addresses) > 0 { + return device.Name + } + } + return devices[0].Name +} + func main() { var targetMAC string var iface string + var listReq bool // Argument parsing args := []string{} @@ -87,6 +232,8 @@ func main() { if arg == "-h" || arg == "--help" { printHelp() return + } else if arg == "-l" || arg == "--list" { + listReq = true } else if arg == "-i" { if i+1 < len(os.Args) { iface = os.Args[i+1] @@ -114,27 +261,30 @@ func main() { targetMAC = "" // Empty = show all } - // Find interface if not specified - if iface == "" { - devices, err := pcap.FindAllDevs() - if err != nil { - log.Fatal("Error finding devices:", err) - } - if len(devices) == 0 { - log.Fatal("No network interfaces found") - } + // Enumerate interfaces (needed for --list, auto-detect and -i resolution). + devices, err := pcap.FindAllDevs() + if err != nil { + log.Fatal("Error finding devices:", err) + } + if len(devices) == 0 { + log.Fatal("No network interfaces found") + } - // Find first non-loopback interface with addresses - for _, device := range devices { - if len(device.Addresses) > 0 && device.Name != "lo" { - iface = device.Name - break - } - } + if listReq { + listInterfaces(devices) + return + } - if iface == "" { - iface = devices[0].Name + if iface == "" { + // Auto-detect a sensible default interface. + iface = autoSelectInterface(devices) + } else { + // Resolve -i value (name, index or description). + resolved, err := resolveInterface(devices, iface) + if err != nil { + log.Fatal("Error selecting interface: ", err) } + iface = resolved } // Open interface for sniffing diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..a7d6079 --- /dev/null +++ b/main_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "net" + "testing" + + "github.com/google/gopacket/pcap" +) + +// windowsDevices simulates what Npcap returns on Windows: opaque +// \Device\NPF_{GUID} names with human-readable descriptions, plus a loopback +// adapter that is NOT named "lo" and a virtual adapter with only a link-local +// (APIPA) address. +func windowsDevices() []pcap.Interface { + return []pcap.Interface{ + { + Name: `\Device\NPF_Loopback`, + Description: "Adapter for loopback traffic capture", + Flags: pcapIfLoopback, + Addresses: []pcap.InterfaceAddress{{IP: net.IPv4(127, 0, 0, 1)}}, + }, + { + Name: `\Device\NPF_{11111111-1111-1111-1111-111111111111}`, + Description: "VirtualBox Host-Only Ethernet Adapter", + Addresses: []pcap.InterfaceAddress{{IP: net.IPv4(169, 254, 3, 4)}}, // APIPA + }, + { + Name: `\Device\NPF_{22222222-2222-2222-2222-222222222222}`, + Description: "Intel(R) Ethernet Connection I219-V", + Addresses: []pcap.InterfaceAddress{{IP: net.IPv4(192, 168, 1, 50)}}, + }, + } +} + +func TestAutoSelectSkipsLoopbackAndAPIPA(t *testing.T) { + got := autoSelectInterface(windowsDevices()) + want := `\Device\NPF_{22222222-2222-2222-2222-222222222222}` + if got != want { + t.Errorf("autoSelectInterface() = %q, want the routable Intel adapter %q", got, want) + } +} + +func TestResolveByDescription(t *testing.T) { + got, err := resolveInterface(windowsDevices(), "Intel") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := `\Device\NPF_{22222222-2222-2222-2222-222222222222}` + if got != want { + t.Errorf("resolveInterface(\"Intel\") = %q, want %q", got, want) + } +} + +func TestResolveByIndex(t *testing.T) { + got, err := resolveInterface(windowsDevices(), "3") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := `\Device\NPF_{22222222-2222-2222-2222-222222222222}` + if got != want { + t.Errorf("resolveInterface(\"3\") = %q, want %q", got, want) + } +} + +func TestResolveByExactName(t *testing.T) { + name := `\Device\NPF_{11111111-1111-1111-1111-111111111111}` + got, err := resolveInterface(windowsDevices(), name) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != name { + t.Errorf("resolveInterface(exact) = %q, want %q", got, name) + } +} + +func TestResolveAmbiguous(t *testing.T) { + // "Adapter" appears in multiple descriptions. + if _, err := resolveInterface(windowsDevices(), "Adapter"); err == nil { + t.Error("expected ambiguity error, got nil") + } +} + +func TestResolveOutOfRange(t *testing.T) { + if _, err := resolveInterface(windowsDevices(), "99"); err == nil { + t.Error("expected out-of-range error, got nil") + } +} + +func TestResolveNoMatch(t *testing.T) { + if _, err := resolveInterface(windowsDevices(), "nonexistent"); err == nil { + t.Error("expected no-match error, got nil") + } +} + +func TestIsLoopbackByFlagAndDescription(t *testing.T) { + devs := windowsDevices() + if !isLoopback(devs[0]) { + t.Error("expected loopback adapter to be detected via flag/description") + } + if isLoopback(devs[2]) { + t.Error("Intel adapter wrongly detected as loopback") + } +}