-
Notifications
You must be signed in to change notification settings - Fork 0
/
alive.go
63 lines (54 loc) · 1.05 KB
/
alive.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
package rtsp
import (
"fmt"
"net"
"strings"
"sync"
"github.com/cheggaaa/pb/v3"
)
type IPAddr struct {
IP string
Port string
}
func (r *Runner) CheckAlive(targets []string) (results []IPAddr) {
var tasks []IPAddr
for _, target := range targets {
parts := strings.Split(target, ":")
if len(parts) != 2 {
continue
}
tasks = append(tasks, IPAddr{
IP: parts[0],
Port: parts[1],
})
}
wg := &sync.WaitGroup{}
rwMutex := &sync.RWMutex{}
taskChan := make(chan IPAddr, r.options.Threads)
for i := 0; i < r.options.Threads; i++ {
go func() {
for task := range taskChan {
if r.conn(task) {
rwMutex.Lock()
results = append(results, task)
rwMutex.Unlock()
}
wg.Done()
}
}()
}
bar := pb.StartNew(len(tasks))
for _, task := range tasks {
bar.Increment()
wg.Add(1)
taskChan <- task
}
close(taskChan)
wg.Wait()
bar.Finish()
return
}
func (r *Runner) conn(ipAddr IPAddr) bool {
_, err := net.DialTimeout("tcp", fmt.Sprintf("%v:%v", ipAddr.IP, ipAddr.Port), r.options.Timeout)
return err == nil
}