go 读取ip文件 进行循环ping检查

 

package main

import (
	"fmt"
	"github.com/tatsushid/go-fastping"
	"io/ioutil"
	"net"
	"os"
	"strings"
	"time"
)


func main() {
	var result []string
	b, err := ioutil.ReadFile("ip")
	if err != nil {
	}
	s := string(b)
	for _, lineStr := range strings.Split(s, "\n") {
		lineStr = strings.TrimSpace(lineStr)
		if lineStr == "" {
			continue
		}
		result = append(result, lineStr)
	}
	for _, v := range result {
		p := fastping.NewPinger()
		ra, err := net.ResolveIPAddr("ip4:icmp", v)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		p.AddIPAddr(ra)
		var d int
		p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
			d = 1
		}
		p.OnIdle = func() {
			if d == 1 {
				fmt.Println(v, "ok")
			} else {
				fmt.Println(v, "no")
			}
		}
		err = p.Run()
		if err != nil {
			fmt.Println(err)
		}
	}
}
上一篇:Go 语言接口详解(一)


下一篇:个人项目