mirror of
https://github.com/go-ping/ping.git
synced 2025-08-31 12:52:04 +00:00
fix: fix not exist interface
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
6
ping.go
6
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)
|
||||
}
|
||||
|
@@ -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
|
||||
|
Reference in New Issue
Block a user