-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (64 loc) · 1.75 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
package main
import (
"bufio"
"flag"
"fmt"
"net"
"os"
"strconv"
"sync"
"time"
)
func main() {
// Define the command-line flags
var hostname string
var startPort, endPort int
var timeout time.Duration
flag.StringVar(&hostname, "hostname", "", "The hostname or IP address to scan")
flag.IntVar(&startPort, "start-port", 1, "The start of the port range to scan")
flag.IntVar(&endPort, "end-port", 65535, "The end of the port range to scan")
flag.DurationVar(&timeout, "timeout", time.Second, "The timeout for connection attempts")
flag.Parse()
// Validate the port range
if startPort > endPort {
fmt.Println("Invalid port range:", startPort, "-", endPort)
os.Exit(1)
}
// Set up a wait group to track the goroutines
var wg sync.WaitGroup
// Set up counters for open and closed ports
var openPorts, closedPorts int
// Start a timer
startTime := time.Now()
// Scan the ports
fmt.Println("Scanning ports", startPort, "to", endPort, "on", hostname)
for port := startPort; port <= endPort; port++ {
wg.Add(1)
go func(port int) {
defer wg.Done()
address := hostname + ":" + strconv.Itoa(port)
conn, err := net.DialTimeout("tcp", address, timeout)
if err == nil {
defer conn.Close()
banner, err := bufio.NewReader(conn).ReadString('\n')
if err == nil {
fmt.Println(address, "is open (service:", banner, ")")
} else {
fmt.Println(address, "is open")
}
openPorts++
} else {
closedPorts++
}
}(port)
}
// Wait for all the goroutines to complete
wg.Wait()
// Stop the timer
elapsedTime := time.Since(startTime)
// Print the results
fmt.Println("Scan complete.")
fmt.Println("Open ports:", openPorts)
fmt.Println("Closed ports:", closedPorts)
fmt.Println("Total time elapsed:", elapsedTime)
}