This repository was archived by the owner on Dec 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpingGo.go
94 lines (82 loc) · 2.08 KB
/
pingGo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"fmt"
"net"
"time"
"os"
"github.com/tatsushid/go-fastping"
"log"
"bufio"
"path/filepath"
)
const fileName = "hosts/hosts.txt"
func main() {
ticker := time.NewTicker(time.Second * 5)
go func (){
for range ticker.C {
lines, err := readFile()
if err != nil {
fmt.Println("Open file: ", err)
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
// log.Fatalf("readLines: %s", err)
}else{
startPinging(lines)
ticker.Stop()
fmt.Println("First Ticker stopped")
}
}
}()
time.Sleep(time.Second * 100)
ticker.Stop()
fmt.Println("Ticker stopped")
}
func readFile() ([]string, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func startPinging(hostAddress []string){
ticker := time.NewTicker(time.Second * 5)
go func() {
for t := range ticker.C {
for i, line := range hostAddress {
fmt.Println(i+1, line + " " + t.String() )
fmt.Printf("Tick at %s , result is %s \n", t, ping(line))
}
fmt.Println()
}
}()
time.Sleep(time.Second * 55)
ticker.Stop()
fmt.Println("Ticker stopped")
}
func ping(hostAddress string)(string){
p := fastping.NewPinger()
ra, err := net.ResolveIPAddr("ip4:icmp", hostAddress)
if err != nil {
fmt.Println(err)
return err.Error()
//os.Exit(1)
}
p.AddIPAddr(ra)
p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
fmt.Printf("IP Addr: %s receive, RTT: %v\n", addr.String(), rtt)
}
err = p.Run()
if err != nil {
return err.Error()
}
return "Ok"
}