Pinging from cmd

Issue

I have this app that needs to ping google.com to see if the network connection is alive.

The following works code fine and lists the directory content:

cmd = exec.Command("ls", "-lah")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
    log.Fatalf("cmd.Run() failed with %s\n", err)
}
outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)

When I change the args this hangs.

cmd = exec.Command("ping", "goole.com")

This causes an error: cmd.Run() failed with exit status 2

cmd = exec.Command("ping", "https://www.goole.com")

After i changed the args to:

cmd = exec.Command("ping -c 5", "goole.com")

I get

cmd.Run() failed with exec: "ping -c 5": executable file not found in
$PATH

I’m using go mod for my dependencies.
Any idea what I do wrong?

Solution

  1. The error is because you mention https. Try running as

cmd = exec.Command("ping", "www.google.com") or simply "google.com" should work too.

  1. The reason the first one hangs is because you’re calling ping without any other args which runs pings infinitely. So try calling it with args -c which mentions the count.
    This should work.

cmd := exec.Command("ping", "-c" , "3", "google.com")

Even better, make it faster with a smaller interval -i 0.1 or something that you see fit. But ensure you add the -c.

Answered By – padfoot

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.