Pinging from cmd


I have this app that needs to ping 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", "")

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

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

After i changed the args to:

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

I get

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

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


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

cmd = exec.Command("ping", "") or simply "" 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", "")

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.