-
Notifications
You must be signed in to change notification settings - Fork 1
/
scanner.go
84 lines (76 loc) · 1.62 KB
/
scanner.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
package main
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
mcpinger "github.com/Raqbit/mc-pinger"
)
func scanIps() {
scanning = true
var mutex sync.Mutex
if *verbose {
log.Println("Starting IP scanner...")
}
for {
for scanWorkers >= maxScanWorkers {
time.Sleep(100 * time.Millisecond)
}
address := <-scanQueue
if address == "end" {
break
}
ip := address
var port uint16 = 25565
if strings.Contains(address, ":") {
segments := strings.Split(address, ":")
ip = segments[0]
parsedPort, _ := strconv.ParseUint(segments[1], 10, 16)
port = uint16(parsedPort)
}
go scanIp(ip, port, &mutex)
mutex.Lock()
scanWorkers++
scanned++
mutex.Unlock()
}
for scanWorkers > 0 {
time.Sleep(1 * time.Millisecond)
}
scanning = false
}
func scanIp(ip string, port uint16, mutex *sync.Mutex) {
if *verbose {
log.Printf("Scanning %v:%v...\n", ip, port)
}
response, err := mcpinger.New(ip, port, mcpinger.WithTimeout(time.Second*time.Duration(timeout))).Ping()
if err != nil {
if *verbose {
log.Printf("Unable to scan %v:%v: %v\n", ip, port, err.Error())
}
mutex.Lock()
scanWorkers--
mutex.Unlock()
return
}
jsonObject, err := json.Marshal(response)
if err != nil {
log.Printf("Unable to marshal server response: %v\n", err.Error())
mutex.Lock()
scanWorkers--
mutex.Unlock()
return
}
log.Printf("Found Minecraft server at %v:%v\n", ip, port)
err = database.Write(fmt.Sprintf("%v:%v", ip, port), jsonObject)
if err != nil {
log.Printf("Unable to write to database: %v\n", err.Error())
}
mutex.Lock()
scanWorkers--
valid++
mutex.Unlock()
}