Here’s a function in Golang that checks if an IP address is alive or not using ICMP and returns a boolean value:
package main
import (
"fmt"
"net"
"os"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
)
func IsIPAlive(ip string) bool {
conn, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer conn.Close()
dstAddr, err := net.ResolveIPAddr("ip4", ip)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
msg := icmp.Message{
Type: ipv4.ICMPTypeEcho,
Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff,
Seq: 1,
Data: []byte("HELLO-R-U-THERE"),
},
}
msgBytes, err := msg.Marshal(nil)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
_, err = conn.WriteTo(msgBytes, dstAddr)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
buffer := make([]byte, 1024)
// Wait for a response with a timeout of 2 seconds
conn.SetReadDeadline(time.Now().Add(time.Second * 2))
_, _, err = conn.ReadFrom(buffer)
if err != nil {
return false
} else {
return true
}
}
func main() {
ipAddr := "8.8.8.8" // example IP address
alive := IsIPAlive(ipAddr)
fmt.Println(alive) // prints true if the IP is alive, false otherwise
}




