Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pinging from cmd

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading