forked from handy-golang/goTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetIPS.go
104 lines (89 loc) · 1.94 KB
/
GetIPS.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
package mVerify
import (
_ "embed"
"fmt"
"strings"
"github.com/EasyGolang/goTools/mStr"
"github.com/gocolly/colly"
)
type IPAddressType struct {
Hostname string
ISP string
Operators string
}
func GetIPS(ips []string) []IPAddressType {
rList := []IPAddressType{}
for _, val := range ips {
res, _ := GetIPaddress(val)
if len(res.Hostname) > 0 {
rList = append(rList, res)
}
}
return rList
}
/*
https://www.ipshudi.com/36.44.232.38.htm
*/
func GetIPaddress(ip string) (resData IPAddressType, resErr error) {
if !IsIP(ip) {
resErr = fmt.Errorf("ip地址不正确")
return
}
HeaderMap := FileToHeader(WhatIsMyIpHeader)
c := colly.NewCollector()
c.OnRequest(func(r *colly.Request) {
for key, val := range HeaderMap {
r.Headers.Set(key, val)
}
})
c.OnError(func(r *colly.Response, errStr error) {
resErr = errStr
})
// 获取IP
c.OnHTML(".input-text", func(e *colly.HTMLElement) {
value := e.Attr("value")
resData.Hostname = value
})
// 获取运营商和归属地
c.OnHTML("td.th+td", func(e *colly.HTMLElement) {
isA := e.DOM.Find(".report")
if len(isA.Text()) > 0 {
span := e.DOM.Find("span")
resData.ISP = span.Text()
} else {
span := e.DOM.Find("span")
resData.Operators = span.Text()
}
})
tmplStr := `https://www.ipshudi.com/${IP}.htm`
tmplVal := map[string]string{
"IP": ip,
}
FetchUrl := mStr.Temp(tmplStr, tmplVal)
c.Visit(FetchUrl)
if resErr != nil {
return
}
// 请求完成
if !IsIP(resData.Hostname) {
resErr = fmt.Errorf("未获取到指定IP")
return
}
return
}
// ========= 解析 Header 头 ===============
//go:embed WhatIsMyIpHeader.yaml
var WhatIsMyIpHeader string
func FileToHeader(cont string) map[string]string {
strArr := strings.Split(cont, "\n")
HeaderMap := make(map[string]string)
for _, item := range strArr {
kvArr := strings.Split(item, ": ")
if len(kvArr) == 2 {
k := kvArr[0]
v := kvArr[1]
HeaderMap[k] = v
}
}
return HeaderMap
}