Home > Net >  Pinging from cmd
Pinging from cmd

Time:03-15

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?

CodePudding user response:

  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.

CodePudding user response:

The ping command runs indefinitely, which is why it appears to hang - ping never exits. You can force it to exit by limiting the number of ping attempts with the -c argument, e.g.

ping -c 5 goole.com will attempt 5 pings. This is the shell form. In your code, use:

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

https://www.goole.com fails because ping expects a host name, not a URL.

CodePudding user response:

Why would you spawn a process to ping an IP address? Try go-ping, one of several packages that implement ICMP ping.

  • Related