-
Notifications
You must be signed in to change notification settings - Fork 1
/
scanPorts.go
77 lines (67 loc) · 1.68 KB
/
scanPorts.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
package main
import (
"net"
"strconv"
"sync"
"time"
)
func isPortOpen(ip string, port int) bool {
// Simple check: attempt a TCP dial.
target := ip + ":" + strconv.Itoa(port)
conn, err := net.DialTimeout("tcp", target, 1*time.Second)
if err != nil {
return false
}
conn.Close()
return true
}
// regular scanPorts function without nmap
// func scanPorts(ip string) []int {
// var wg sync.WaitGroup
// var mutex sync.Mutex
// var openPorts []int
// const startPort = 1 // Adjust as necessary
// const endPort = 65535 // Adjust as necessary
// for port := startPort; port <= endPort; port++ {
// wg.Add(1)
// go func(p int) {
// defer wg.Done()
// if isPortOpen(ip, p) {
// mutex.Lock()
// openPorts = append(openPorts, p)
// mutex.Unlock()
// }
// }(port)
// }
// wg.Wait()
// return openPorts
// }
func scanPortsNmap(ip string) []NmapPortInfo {
// This function uses Nmap to scan for open ports.
var wg sync.WaitGroup
var mutex sync.Mutex
var openPortsInfo []NmapPortInfo
const startPort = 1 // Adjust as necessary
const endPort = 65535 // Adjust as necessary
for port := startPort; port <= endPort; port++ {
wg.Add(1)
go func(p int) {
defer wg.Done()
if isPortOpen(ip, p) {
mutex.Lock()
portInfo := NmapPortInfo{
Port: p,
// Since we're only using "tcp" in isPortOpen:
Protocol: "tcp",
// We don't know the service name from this function,
// so keeping it blank.
Service: NmapService{Name: ""},
}
openPortsInfo = append(openPortsInfo, portInfo)
mutex.Unlock()
}
}(port)
}
wg.Wait()
return openPortsInfo
}