From 682d8849a80062e9a5558b5bb02b274a9c88fb71 Mon Sep 17 00:00:00 2001 From: ilolicon <97431110@qq.com> Date: Tue, 11 Apr 2023 19:37:37 +0800 Subject: [PATCH] fix: fix not exist interface --- packetconn.go | 14 +++++--------- ping.go | 6 +++++- ping_test.go | 4 +++- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packetconn.go b/packetconn.go index 3ffa29b..7f03120 100644 --- a/packetconn.go +++ b/packetconn.go @@ -18,7 +18,7 @@ type packetConn interface { SetReadDeadline(t time.Time) error WriteTo(b []byte, dst net.Addr) (int, error) SetTTL(ttl int) - SetIfaceIndex(iface string) + SetIfaceIndex(ifaceIndex int) } type icmpConn struct { @@ -35,12 +35,8 @@ func (c *icmpConn) SetTTL(ttl int) { c.ttl = ttl } -func (c *icmpConn) SetIfaceIndex(iface string) { - i, err := net.InterfaceByName(iface) - if err != nil { - c.ifaceIndex = 0 - } - c.ifaceIndex = i.Index +func (c *icmpConn) SetIfaceIndex(ifaceIndex int) { + c.ifaceIndex = ifaceIndex } func (c *icmpConn) SetReadDeadline(t time.Time) error { @@ -78,7 +74,7 @@ func (c *icmpv4Conn) WriteTo(b []byte, dst net.Addr) (int, error) { } var cm *ipv4.ControlMessage if 1 <= c.ifaceIndex { - // set interface + // If not set interface c.ifaceIndex == 0 if err := c.c.IPv4PacketConn().SetControlMessage(ipv4.FlagInterface, true); err != nil { return 0, err } @@ -119,7 +115,7 @@ func (c *icmpV6Conn) WriteTo(b []byte, dst net.Addr) (int, error) { } var cm *ipv6.ControlMessage if 1 <= c.ifaceIndex { - // set interface + // If not set interface c.ifaceIndex == 0 if err := c.c.IPv6PacketConn().SetControlMessage(ipv6.FlagInterface, true); err != nil { return 0, err } diff --git a/ping.go b/ping.go index ba10728..d538935 100644 --- a/ping.go +++ b/ping.go @@ -422,7 +422,11 @@ func (p *Pinger) Run() error { conn.SetTTL(p.TTL) if p.Iface != "" { - conn.SetIfaceIndex(p.Iface) + iface, err := net.InterfaceByName(p.Iface) + if err != nil { + return err + } + conn.SetIfaceIndex(iface.Index) } return p.run(conn) } diff --git a/ping_test.go b/ping_test.go index 2a99b3b..6a9d1e3 100644 --- a/ping_test.go +++ b/ping_test.go @@ -480,6 +480,8 @@ func TestStatisticsLossy(t *testing.T) { func TestSetIfaceName(t *testing.T) { pinger := New("www.google.com") pinger.Count = 1 + pinger.Timeout = time.Second + pinger.SetPrivileged(true) // Set loopback interface pinger.Iface = "lo" @@ -662,7 +664,7 @@ func (c testPacketConn) ICMPRequestType() icmp.Type { return ipv4.ICMPTyp func (c testPacketConn) SetFlagTTL() error { return nil } func (c testPacketConn) SetReadDeadline(t time.Time) error { return nil } func (c testPacketConn) SetTTL(t int) {} -func (c testPacketConn) SetIfaceIndex(iface string) {} +func (c testPacketConn) SetIfaceIndex(ifaceIndex int) {} func (c testPacketConn) ReadFrom(b []byte) (n int, ttl int, src net.Addr, err error) { return 0, 0, nil, nil