-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (102 loc) · 2.17 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"flag"
"fmt"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"syscall"
"time"
)
var (
successCount int
successMax *int
startTime int64
port *int
)
func TCPPing(IP string, port *int, waitTimeout time.Duration) {
conn, err := net.DialTimeout("tcp", IP+":"+strconv.Itoa(*port), waitTimeout*time.Second)
if err != nil {
//fmt.Printf("\r\033[2KPort %v closed (worker: %v)", i, workerID)
} else {
conn.Close()
successCount++
output := fmt.Sprintf("Port %v open", *port)
fmt.Print(output + "\n")
output = "The Internet's on!"
cmd := exec.Command("say", "-v", "Good News", output)
cmd.Run()
if successCount < *successMax {
time.Sleep(waitTimeout * time.Second)
}
}
}
func IPFormat(IP string) string {
for i := 0; i < len(IP); i++ {
switch IP[i] {
case '.':
return ("IPv4")
case ':':
return ("IPv6")
}
}
return ""
}
func checkValidIP(IP string) {
if net.ParseIP(IP) == nil {
fmt.Printf("Invalid IP Address: %s\n", IP)
os.Exit(1)
}
}
func min(a, b int) int {
if a <= b {
return a
}
return b
}
func handleSIGTERM() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Printf("\n\nPing cancelled\n")
stats()
os.Exit(0)
}()
}
func stats() {
td := time.Now()
endTime := td.Unix()
timeTaken := endTime - startTime
fmt.Printf("\r\nPinged port %v for %v seconds.\n", *port, timeTaken)
}
func main() {
handleSIGTERM()
usage := fmt.Sprintf("Usage: %s -p <port> -s <stop after X successful pings>-w <wait timeout> <ip address>\n", filepath.Base(os.Args[0]))
argLength := len(os.Args[1:])
if argLength < 1 {
fmt.Printf(usage)
os.Exit(1)
}
//set defaults
port = flag.Int("p", 80, "start port")
successMax = flag.Int("s", 3, "stop after X successful pings")
waitTimeout := flag.Int64("w", 30, "Wait timeout")
flag.Parse()
IP := flag.Arg(0)
checkValidIP(IP)
if *port < 0 || *port > 65535 {
*port = 80
}
successCount = 0
fmt.Printf("TCP Ping %s (%s) Port %v\n\n", IP, IPFormat(IP), *port)
td := time.Now()
startTime = td.Unix()
for successCount < *successMax {
TCPPing(IP, port, time.Duration(*waitTimeout))
}
stats()
}