From 244178e5ca7600d9b7c3096774a74e4020ea75c0 Mon Sep 17 00:00:00 2001 From: Sebastian Spaink <3441183+sspaink@users.noreply.github.com> Date: Thu, 28 Jan 2021 11:30:00 -0600 Subject: [PATCH] Set interface for native (#8770) Support both name and IP --- plugins/inputs/ping/ping.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/plugins/inputs/ping/ping.go b/plugins/inputs/ping/ping.go index 7550559dd..1bec73f4e 100644 --- a/plugins/inputs/ping/ping.go +++ b/plugins/inputs/ping/ping.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "math" + "net" "os/exec" "runtime" "strings" @@ -29,6 +30,8 @@ type Ping struct { calcInterval time.Duration calcTimeout time.Duration + sourceAddress string + Log telegraf.Logger `toml:"-"` // Interval at which to ping (ping -i ) @@ -171,6 +174,7 @@ func (p *Ping) nativePing(destination string) (*pingStats, error) { pinger.SetNetwork("ip6") } + pinger.Source = p.sourceAddress pinger.Interval = p.calcInterval pinger.Timeout = p.calcTimeout @@ -310,6 +314,23 @@ func (p *Ping) Init() error { p.calcTimeout = time.Duration(p.Timeout) * time.Second } + // Support either an IP address or interface name + if p.Interface != "" { + if addr := net.ParseIP(p.Interface); addr != nil { + p.sourceAddress = p.Interface + } else { + i, err := net.InterfaceByName(p.Interface) + if err != nil { + return fmt.Errorf("Failed to get interface: %w", err) + } + addrs, err := i.Addrs() + if err != nil { + return fmt.Errorf("Failed to get the address of interface: %w", err) + } + p.sourceAddress = addrs[0].(*net.IPNet).IP.String() + } + } + return nil }