-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
173 lines (141 loc) · 5.37 KB
/
main.go
File metadata and controls
173 lines (141 loc) · 5.37 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"fmt"
"net"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/fatih/color"
)
// Statistics holds connection statistics
type Statistics struct {
Total int
Successful int
Failed int
TotalLatency float64
}
func printBanner() {
cyan := color.New(color.FgCyan).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
fmt.Printf("\n%s\n", cyan("╔═══════════════════════════════════════╗"))
fmt.Printf("%s %s %s\n", cyan("║"), yellow("⚡ TCPing - TCP Port Tester ⚡"), cyan("║"))
fmt.Printf("%s\n\n", cyan("╚═══════════════════════════════════════╝"))
}
func validateArgs() (string, int) {
if len(os.Args) != 3 {
color.Red("✗ Error: Invalid arguments")
color.Yellow("Usage: %s <ip> <port>", os.Args[0])
color.Cyan("Example: %s 8.8.8.8 53", os.Args[0])
os.Exit(1)
}
host := os.Args[1]
port, err := strconv.Atoi(os.Args[2])
if err != nil || port < 1 || port > 65535 {
color.Red("✗ Error: Port must be a number between 1 and 65535")
os.Exit(1)
}
return host, port
}
func tcping(host string, port int, timeout time.Duration) (bool, float64, string) {
address := fmt.Sprintf("%s:%d", host, port)
start := time.Now()
conn, err := net.DialTimeout("tcp", address, timeout)
elapsed := time.Since(start).Seconds() * 1000 // Convert to milliseconds
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
return false, elapsed, "Timeout"
}
return false, elapsed, "Connection refused"
}
conn.Close()
return true, elapsed, ""
}
func getLatencyColor(latency float64) *color.Color {
if latency < 50 {
return color.New(color.FgGreen)
} else if latency < 150 {
return color.New(color.FgYellow)
}
return color.New(color.FgRed)
}
func printStatistics(stats Statistics, host string, port int) {
cyan := color.New(color.FgCyan).SprintFunc()
white := color.New(color.FgWhite).SprintFunc()
green := color.New(color.FgGreen).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
fmt.Printf("\n\n%s\n", cyan("────────────────────────────────────────────────────────────"))
fmt.Printf("%s\n", yellow(fmt.Sprintf("📊 Statistics for %s:%d", host, port)))
fmt.Printf("%s\n", cyan("────────────────────────────────────────────────────────────"))
if stats.Total > 0 {
successRate := float64(stats.Successful) / float64(stats.Total) * 100
fmt.Printf("%s %s\n", white("Total probes:"), cyan(fmt.Sprintf("%d", stats.Total)))
fmt.Printf("%s %s\n", white("Successful:"), green(fmt.Sprintf("%d", stats.Successful)))
fmt.Printf("%s %s\n", white("Failed:"), red(fmt.Sprintf("%d", stats.Failed)))
fmt.Printf("%s %s\n", white("Success rate:"), yellow(fmt.Sprintf("%.1f%%", successRate)))
if stats.Successful > 0 {
avgLatency := stats.TotalLatency / float64(stats.Successful)
latencyColor := getLatencyColor(avgLatency)
fmt.Printf("%s %s\n", white("Average latency:"), latencyColor.Sprintf("%.2fms", avgLatency))
}
}
fmt.Printf("%s\n", cyan("────────────────────────────────────────────────────────────"))
color.Green("✓ TCPing terminated\n")
}
func main() {
printBanner()
host, port := validateArgs()
color.Cyan("Target: %s", color.WhiteString("%s:%d", host, port))
color.Cyan("Timeout: %s", color.WhiteString("3 seconds"))
color.Cyan("────────────────────────────────────────────────────────────\n")
stats := Statistics{}
seq := 0
// Setup signal handling for Ctrl+C
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Ticker for periodic pings
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
// Channel to signal done
done := make(chan bool)
go func() {
for {
select {
case <-ticker.C:
seq++
timestamp := time.Now().Format("15:04:05")
success, latency, errorMsg := tcping(host, port, 3*time.Second)
stats.Total++
white := color.New(color.FgWhite).SprintFunc()
cyan := color.New(color.FgCyan).SprintFunc()
if success {
stats.Successful++
stats.TotalLatency += latency
latencyColor := getLatencyColor(latency)
fmt.Printf("%s %s Connected to %s - seq=%d time=%s\n",
white(fmt.Sprintf("[%s]", timestamp)),
color.GreenString("✓"),
cyan(fmt.Sprintf("%s:%d", host, port)),
seq,
latencyColor.Sprintf("%.2fms", latency))
} else {
stats.Failed++
fmt.Printf("%s %s Cannot reach destination %s - %s\n",
white(fmt.Sprintf("[%s]", timestamp)),
color.RedString("✗"),
color.RedString("%s:%d", host, port),
color.RedString(errorMsg))
}
case <-done:
return
}
}
}()
// Wait for interrupt signal
<-sigChan
done <- true
time.Sleep(100 * time.Millisecond) // Give time for last message to print
printStatistics(stats, host, port)
}