Debian Codegraph @

pkg/testutils/ping.go

raw symbols SCIP
1 // Copyright 2017 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package testutils
16
17 import (
18 "bytes"
19 "fmt"
20 "net"
21 "os/exec"
22 "strconv"
23 "syscall"
24 )
25
26 // Ping shells out to the `ping` command. Returns nil if successful.
27 func Ping(saddr, daddr string, timeoutSec int) error {
28 ip := net.ParseIP(saddr)
29 if ip == nil {
30 return fmt.Errorf("failed to parse IP %q", saddr)
31 }
32
33 bin := "ping6"
34 if ip.To4() != nil {
35 bin = "ping"
36 }
37
38 args := []string{
39 "-c", "1",
40 "-W", strconv.Itoa(timeoutSec),
41 "-I", saddr,
42 daddr,
43 }
44
45 cmd := exec.Command(bin, args...)
46 var stderr bytes.Buffer
47 cmd.Stderr = &stderr
48
49 if err := cmd.Run(); err != nil {
50 switch e := err.(type) {
51 case *exec.ExitError:
52 return fmt.Errorf("%v exit status %d: %s",
53 args, e.Sys().(syscall.WaitStatus).ExitStatus(),
54 stderr.String())
55 default:
56 return err
57 }
58 }
59
60 return nil
61 }