Skip to content

Commit

Permalink
fix(inputs.ping): Check addr length to avoid crash (#15601)
Browse files Browse the repository at this point in the history
  • Loading branch information
powersj authored Jul 10, 2024
1 parent a768de8 commit 3a05c38
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions plugins/inputs/ping/ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,26 @@ func (p *Ping) nativePing(destination string) (*pingStats, error) {
}
}

// Support either an IP address or interface name
if p.Interface != "" && p.sourceAddress == "" {
if addr := net.ParseIP(p.Interface); addr != nil {
p.sourceAddress = p.Interface
} else {
i, err := net.InterfaceByName(p.Interface)
if err != nil {
return nil, fmt.Errorf("failed to get interface: %w", err)
}
addrs, err := i.Addrs()
if err != nil {
return nil, fmt.Errorf("failed to get the address of interface: %w", err)
}
if len(addrs) == 0 {
return nil, fmt.Errorf("no address found for interface %s", p.Interface)
}
p.sourceAddress = addrs[0].(*net.IPNet).IP.String()
}
}

pinger.Source = p.sourceAddress
pinger.Interval = p.calcInterval

Expand Down Expand Up @@ -292,23 +312,6 @@ 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
}

Expand Down

0 comments on commit 3a05c38

Please sign in to comment.