From 72dfce2120d48b39a6d607db54b709102a2444ef Mon Sep 17 00:00:00 2001 From: TimofeyAf Date: Tue, 22 Feb 2022 23:49:57 +0300 Subject: [PATCH] Add ability to set outgouing interface (only Linux support). Review --- packetconn.go | 35 ----------------------------------- utils_linux.go | 2 +- utils_other.go | 4 +++- utils_windows.go | 2 +- 4 files changed, 5 insertions(+), 38 deletions(-) diff --git a/packetconn.go b/packetconn.go index 0c9bfd9..46428be 100644 --- a/packetconn.go +++ b/packetconn.go @@ -1,11 +1,8 @@ package ping import ( - "errors" "net" - "reflect" "runtime" - "syscall" "time" "golang.org/x/net/icmp" @@ -41,38 +38,6 @@ func (c *icmpConn) SetReadDeadline(t time.Time) error { return c.c.SetReadDeadline(t) } -func getConnFD(conn *icmp.PacketConn) (fd int) { - var packetConn reflect.Value - - defer func() { - if r := recover(); r != nil { - fd = -1 - } - }() - - if conn.IPv4PacketConn() != nil { - packetConn = reflect.ValueOf(conn.IPv4PacketConn().PacketConn) - } else if conn.IPv6PacketConn() != nil { - packetConn = reflect.ValueOf(conn.IPv6PacketConn().PacketConn) - } else { - return -1 - } - - netFD := reflect.Indirect(reflect.Indirect(packetConn).FieldByName("fd")) - pollFD := netFD.FieldByName("pfd") - systemFD := pollFD.FieldByName("Sysfd") - return int(systemFD.Int()) -} - -func (c *icmpConn) BindToDevice(ifName string) error { - if runtime.GOOS == "linux" { - if fd := getConnFD(c.c); fd >= 0 { - return syscall.BindToDevice(fd, ifName) - } - } - return errors.New("bind to interface unsupported") // FIXME: or nil -} - func (c *icmpConn) WriteTo(b []byte, dst net.Addr) (int, error) { if c.c.IPv6PacketConn() != nil { if err := c.c.IPv6PacketConn().SetHopLimit(c.ttl); err != nil { diff --git a/utils_linux.go b/utils_linux.go index 0ba7677..8cae0ec 100644 --- a/utils_linux.go +++ b/utils_linux.go @@ -1,4 +1,4 @@ -//go:build linux +// +build linux package ping diff --git a/utils_other.go b/utils_other.go index 1bdbdb0..1dd0e77 100644 --- a/utils_other.go +++ b/utils_other.go @@ -1,7 +1,9 @@ -//go:build !linux && !windows +// +build !linux,!windows package ping +import "errors" + // Returns the length of an ICMP message. func (p *Pinger) getMessageLength() int { return p.Size + 8 diff --git a/utils_windows.go b/utils_windows.go index a00ffb7..9339543 100644 --- a/utils_windows.go +++ b/utils_windows.go @@ -1,4 +1,4 @@ -//go:build windows +// +build windows package ping