美文网首页
Golang 模拟ping操作

Golang 模拟ping操作

作者: Sunnky | 来源:发表于2021-09-01 20:24 被阅读0次
    package main
    
    import (
        "fmt"
        "github.com/go-ping/ping"
        "os/exec"
        "time"
    )
    
    func main() {
        pingTest("192.168.1.1")
        pingTest("8.8.8.8")
        conn, err := PingConn("8.8.8.8")
        fmt.Println(conn, err)
    }
    
    func PingConn(addr string) (bool, error) {
        Command := fmt.Sprintf("ping -c 1 -W 3 %s > /dev/null && echo true || echo false", addr)
        output, err := exec.Command("/bin/sh","-c", Command).Output()
        return string(output) == "true\n", err
    }
    
    func pingTest(ip string)  {
        pinger, err := ping.NewPinger(ip)
        if err != nil {
            panic(err)
        }
        pinger.Debug = true
        pinger.OnFinish = func(statistics *ping.Statistics) {
            fmt.Printf("OnFinish: %#v\n", statistics)
        }
        pinger.OnRecv = func(packet *ping.Packet) {
            fmt.Printf("OnRecv: %#v\n", packet)
        }
        pinger.Timeout = time.Second * 3
        pinger.Count = 3
        pinger.Run() // blocks until finished
    }
    

    相关文章

      网友评论

          本文标题:Golang 模拟ping操作

          本文链接:https://www.haomeiwen.com/subject/ntdfwltx.html