Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down Expand Up @@ -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:
Expand Down
25 changes: 24 additions & 1 deletion README_DE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down Expand Up @@ -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:
Expand Down
186 changes: 168 additions & 18 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"log"
"os"
"strconv"
"strings"
"time"

Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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

Expand All @@ -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 <index|name|description>")
}

// 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{}
Expand All @@ -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]
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading