How to ping an IP Address in golang
@jpillora's answer suggests using go-fastping
, but that library hasn't been updated since Jan 8, 2016. It may not be an issue as the logic of pinging is quite simple, but if you want a more recent package then there's go-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:
https://github.com/tatsushid/go-fastping
Note, sending ICMP packets requires root privileges
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")
}
Although not a real ICMP ping, this is what use to probe my servers using the TCP protocol:
host := "example.com"
port := "80"
timeout := time.Duration(1 * time.Second)
_, err := net.DialTimeout("tcp", host+":"+port, timeout)
if err != nil {
fmt.Printf("%s %s %s\n", host, "not responding", err.Error())
} else {
fmt.Printf("%s %s %s\n", host, "responding on port:", port)
}