Files
NTrace-core/trace/internal/bind_device_linux.go
T
tsosunchia 2a5717aedf Fix explicit source/device handling across platforms
Keep the default traceroute path unchanged when neither --source nor --dev is set so existing source address selection, socket setup, and logging stay untouched.

Add a shared explicit source/device normalization helper and route the CLI traceroute path, standalone --mtu path, fast_trace, and server trace requests through it. The helper keeps --source higher priority than --dev, resolves device-derived source addresses by destination family, rejects devices without a usable address, and emits at most one runtime warning.

On macOS, bind TCP and UDP send sockets to the requested interface with IP_BOUND_IF/IPV6_BOUND_IF so explicit --dev survives utun default routes. On Linux, bind ICMP/TCP/UDP send sockets with SO_BINDTODEVICE only when a source device is explicitly configured.

On Windows, keep the existing no-rewrite constraint for real device binding. Explicit --dev now resolves a source address, clears SourceDevice before the tracer is built, and surfaces a single warning that actual egress still follows system routing.

Update CLI help text and README platform notes to document the supported --dev semantics, and add unit tests that cover no-op behavior without explicit overrides, --source priority, device family resolution, mismatch errors, and the Windows downgrade warning.
2026-04-07 17:00:53 +08:00

37 lines
823 B
Go

//go:build linux
package internal
import (
"fmt"
"net"
"syscall"
)
func bindPacketConnToSourceDevice(conn net.PacketConn, ipVersion int, device string) error {
_ = ipVersion
if conn == nil || device == "" {
return nil
}
sysconn, ok := conn.(syscall.Conn)
if !ok {
return fmt.Errorf("packet conn does not support syscall.Conn")
}
rawConn, err := sysconn.SyscallConn()
if err != nil {
return fmt.Errorf("packet conn SyscallConn: %w", err)
}
var controlErr error
if err := rawConn.Control(func(fd uintptr) {
controlErr = syscall.SetsockoptString(int(fd), syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, device)
}); err != nil {
return fmt.Errorf("packet conn control: %w", err)
}
if controlErr != nil {
return fmt.Errorf("bind packet conn to device %q: %w", device, controlErr)
}
return nil
}