ZBLOG

write a function with golang, parameter is ip addr,check this ip alive or not by icmp,return bool

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
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=5431

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?