使用Golang实现ping检测主机在线的功能

使用"github.com/go-ping/ping"这个第三方库可以非常简单的实现ping功能

package main

import (
    "fmt"
    "os"
    "time"

    "github.com/go-ping/ping"
)

func CheckHostOnline(ipaddr string) bool {
    pinger, err := ping.NewPinger(ipaddr)
    if err != nil {
        fmt.Println(err)
        return false
    }

    pinger.SetPrivileged(true)
    pinger.Count = 1  //ping包数量
    pinger.Timeout = time.Millisecond * 500  //超时
    pinger.Interval = time.Second //发送间隔

    err = pinger.Run()
    if err != nil {
        panic(err)
    }
    stats := pinger.Statistics()

    return stats.PacketsRecv > 0
}

func main() {
    if len(os.Args) < 2 {
        fmt.Println("Please provide the target IP address.")
        return
    }

    ipaddr := os.Args[1] // 获取命令行参数作为要检查的主机IP地址
    fmt.Printf("ping %s\n", ipaddr)
    if CheckHostOnline(ipaddr) {
        fmt.Printf("Host %s is online.\n", ipaddr)
    } else {
        fmt.Printf("Host %s is offline.\n", ipaddr)
    }
}

 

posted @ 2024-01-30 12:11  黑月教主  阅读(97)  评论(0编辑  收藏  举报