Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ping an IP Address in golang

Tags:

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?

like image 785
Ousmane Traore Avatar asked Aug 07 '15 02:08

Ousmane Traore


People also ask

How to get your IP address with Go-lang?

Get IP address (es) with go-lang is a simple command line tool to get your IP address vpn, internal, external, etc. ipinfo -h A longer description that spans multiple lines and likely contains examples and usage of using your application. For example: Cobra is a CLI library for Go that empowers applications.

How to Ping An IP address in Windows?

To ping an IP address in Windows, open the command line tool by pressing the Windows + R buttons on the keyboard. Type CMD in the Run window that pops up and click on OK. This will automatically launch the command line tool: Next, type ping followed by the IP address or domain that you want to connect to. The command should look like this:

How to write ICMP message in Golang?

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.

What is hostname in Golang?

Golang hostname. The hostname is a label assigned to a machine which is connected in Network of machines. Golang standard package net provides functions related to TCP/IP, UDP and DNS related networking related functionalities. The following are various examples related to the hostname and Ip addresses in Go Language.


2 Answers

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

like image 184
jpillora Avatar answered Oct 08 '22 23:10

jpillora


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")
}
like image 30
Kasmetski Avatar answered Oct 08 '22 23:10

Kasmetski