How can you ping an IP address from a golang application? The ultimate goal is to check if a server is online.
Does go have a way in the standard library to implement a network ping?
As @desaipath mentions, there is no way to do this in the standard library. However, you do not need to write the code for yourself - it has already been done:
Note, sending ICMP packets requires root privileges
No.
Go does not have any built-in way to ping a server in standard library. You need to write code by yourself.
For that, you can look into icmp section of golang library. And use this list of control messages, to construct icmp message properly.
But, keep in mind that some server administrator shuts down ping service on their server, for security reason. So, If your goal is to ultimately check if server is online or not, this is not 100% reliable method.
I needed the same thing as you and I've made a workaround (with exec.Command
) for my Raspberry Pi to check if servers are online. Here is the experimental code
out, _ := exec.Command("ping", "192.168.0.111", "-c 5", "-i 3", "-w 10").Output()
if strings.Contains(string(out), "Destination Host Unreachable") {
fmt.Println("TANGO DOWN")
} else {
fmt.Println("IT'S ALIVEEE")
}
package main
import (
"fmt"
"os/exec"
)
func main() {
Command := fmt.Sprintf("ping -c 1 10.2.201.174 > /dev/null && echo true || echo false")
output, err := exec.Command("/bin/sh", "-c", Command).Output()
fmt.Print(string(output))
fmt.Print(err)
}