-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ping.go
76 lines (58 loc) · 1.81 KB
/
ping.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
package main
import (
"fmt"
"net"
"net/http"
"os/exec"
"regexp"
"strings"
"time"
)
func testICMP() (status string, msg string, pingTime string) {
out, err := exec.Command("ping", "-c", "3", *targetUrl).Output()
if err != nil {
return "down", fmt.Sprintf("Error: %v", err), "unknown"
}
output := string(out)
status = "down"
if strings.Contains(output, "received") {
status = "up"
}
packetLossRe := regexp.MustCompile(`(\d+)% packet loss`)
packetLossMatch := packetLossRe.FindStringSubmatch(output)
packetLoss := "unknown"
if len(packetLossMatch) > 0 {
packetLoss = packetLossMatch[1]
}
rttRe := regexp.MustCompile(`rtt min/avg/max/mdev = [\d\.]+/([\d\.]+)/[\d\.]+/[\d\.]+ ms`)
rttMatch := rttRe.FindStringSubmatch(output)
pingTime = "unknown"
if len(rttMatch) > 0 {
pingTime = rttMatch[1]
}
msg = fmt.Sprintf("Packet loss: %s%%", packetLoss)
return status, msg, pingTime
}
func testHTTP(protocol string) (status string, msg string, pingTime string) {
startTime := time.Now()
resp, err := http.Get(fmt.Sprintf("%s://%s", protocol, *targetUrl))
if err != nil {
return "down", fmt.Sprintf("Error: %v", err), "unknown"
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "down", fmt.Sprintf("Status code: %d", resp.StatusCode), "unknown"
}
pingDuration := time.Since(startTime)
return "up", "OK", fmt.Sprintf("%.2f ms", float64(pingDuration.Microseconds())/1000.0)
}
func testTCP() (status string, msg string, pingTime string) {
startTime := time.Now()
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", *targetUrl, *port), time.Second*3)
if err != nil {
return "down", fmt.Sprintf("Error: %v", err), "unknown"
}
defer conn.Close()
pingDuration := time.Since(startTime)
return "up", "OK", fmt.Sprintf("%.2f ms", float64(pingDuration.Microseconds())/1000.0)
}