/
inetaddr.go
108 lines (92 loc) · 1.78 KB
/
inetaddr.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package inetaddr
import (
"fmt"
"net"
"sort"
"sync"
)
var wg sync.WaitGroup
const (
OnlyDNS = iota
OnlyHTTP
BothMethod
)
type kv struct {
Key string
Value int
}
func checkerDns(srv DnsServer, ch chan net.IP) {
defer wg.Done()
ip, err := DnsCheck(srv)
if err != nil {
return
}
ch <- ip
}
func checkerHttp(srv HttpServer, ch chan net.IP) {
defer wg.Done()
ip, err := HttpCheck(srv)
if err != nil {
return
}
ch <- ip
}
func InetAddr(flagCheckType int) string {
messages := make(chan net.IP, len(HttpServerS)+len(DnsServerS))
var sortIP []kv
res := make(map[string]int)
if flagCheckType == OnlyHTTP || flagCheckType == BothMethod {
wg.Add(1)
go func() {
defer wg.Done()
for j := range HttpServerS {
wg.Add(1)
go checkerHttp(HttpServerS[j], messages)
}
}()
}
if flagCheckType == OnlyDNS || flagCheckType == BothMethod {
wg.Add(1)
go func() {
defer wg.Done()
for i := range DnsServerS {
wg.Add(1)
go checkerDns(DnsServerS[i], messages)
}
}()
}
wg.Wait()
close(messages)
for range messages {
ip := <-messages
res[ip.String()] = res[ip.String()] + 1
}
if len(res) == 0 {
return ""
}
for k, v := range res {
sortIP = append(sortIP, kv{k, v})
}
sort.Slice(sortIP, func(i, j int) bool {
return sortIP[i].Value > sortIP[j].Value
})
if len(sortIP) == 0 {
return ""
}
return sortIP[0].Key
}
func IpAddrString(flagCheckType int) (string, error) {
strIP := InetAddr(flagCheckType)
ip := net.ParseIP(strIP)
if ip == nil {
return "", fmt.Errorf("Response error: There is not ip address")
}
return strIP, nil
}
func IpAddrIP(flagCheckType int) (net.IP, error) {
ip := net.ParseIP(InetAddr(flagCheckType))
if ip == nil {
return nil, fmt.Errorf("Response error: There is not ip address ")
}
return ip, nil
}