Set interface for native (#8770)

Support both name and IP
This commit is contained in:
Sebastian Spaink 2021-01-28 11:30:00 -06:00 committed by GitHub
parent 03fe914c59
commit 244178e5ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"math" "math"
"net"
"os/exec" "os/exec"
"runtime" "runtime"
"strings" "strings"
@ -29,6 +30,8 @@ type Ping struct {
calcInterval time.Duration calcInterval time.Duration
calcTimeout time.Duration calcTimeout time.Duration
sourceAddress string
Log telegraf.Logger `toml:"-"` Log telegraf.Logger `toml:"-"`
// Interval at which to ping (ping -i <INTERVAL>) // Interval at which to ping (ping -i <INTERVAL>)
@ -171,6 +174,7 @@ func (p *Ping) nativePing(destination string) (*pingStats, error) {
pinger.SetNetwork("ip6") pinger.SetNetwork("ip6")
} }
pinger.Source = p.sourceAddress
pinger.Interval = p.calcInterval pinger.Interval = p.calcInterval
pinger.Timeout = p.calcTimeout pinger.Timeout = p.calcTimeout
@ -310,6 +314,23 @@ func (p *Ping) Init() error {
p.calcTimeout = time.Duration(p.Timeout) * time.Second 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 return nil
} }