|
1 | 1 | package iputils |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "errors" |
5 | 4 | "io/ioutil" |
6 | 5 | "log" |
7 | 6 | "net" |
@@ -57,54 +56,52 @@ var Ipv6APIUrls = []string{ |
57 | 56 | "http://v6.ipv6-test.com/api/myip.php", |
58 | 57 | } |
59 | 58 |
|
60 | | -func GetMyPublicIpv4() (string, error) { |
| 59 | +func GetMyPublicIpv4() string { |
61 | 60 | for _, url := range Ipv4APIUrls { |
62 | 61 | resp, err := http.Get(url) |
63 | | - if resp != nil && resp.Body != nil { |
64 | | - defer resp.Body.Close() |
65 | | - } |
66 | 62 | if err != nil { |
67 | 63 | log.Printf("get public ipv4 err:%s", err) |
68 | 64 | continue |
69 | 65 | } |
70 | 66 | bytes, err := ioutil.ReadAll(resp.Body) |
71 | 67 | if err != nil { |
72 | 68 | log.Printf("get public ipv4 err:%s", err) |
| 69 | + _ = resp.Body.Close() |
73 | 70 | continue |
74 | 71 | } |
75 | 72 | ipv4 := strings.Replace(string(bytes), "\n", "", -1) |
76 | 73 | ip := net.ParseIP(ipv4) |
77 | 74 | if ip != nil { |
78 | | - log.Println("got ipv4 addr:", ip.String()) |
79 | | - return ip.String(), nil |
| 75 | + _ = resp.Body.Close() |
| 76 | + return ip.String() |
80 | 77 | } |
81 | 78 | } |
82 | | - return "", errors.New("ipv4 not found") |
| 79 | + return "" |
83 | 80 | } |
84 | 81 |
|
85 | | -func GetMyPublicIpv6() (string, error) { |
| 82 | +func GetMyPublicIpv6() string { |
86 | 83 | for _, url := range Ipv6APIUrls { |
87 | 84 | resp, err := http.Get(url) |
88 | | - if resp != nil && resp.Body != nil { |
89 | | - defer resp.Body.Close() |
90 | | - } |
91 | 85 | if err != nil { |
92 | 86 | log.Printf("get public ipv6 err:%s", err) |
93 | 87 | continue |
94 | 88 | } |
| 89 | + // 读取 IPv6 |
95 | 90 | bytes, err := ioutil.ReadAll(resp.Body) |
96 | 91 | if err != nil { |
97 | 92 | log.Printf("get public ipv6 err:%s", err) |
| 93 | + _ = resp.Body.Close() |
98 | 94 | continue |
99 | 95 | } |
| 96 | + // 删除 document.write(xxx) (如有) |
100 | 97 | tmp := strings.Replace(string(bytes), "document.write('", "", -1) |
101 | | - tmp2 := strings.Replace(tmp, "');", "", -1) |
102 | | - ipv6 := strings.Replace(tmp2, "\n", "", -1) |
| 98 | + tmp = strings.Replace(tmp, "');", "", -1) |
| 99 | + ipv6 := strings.Replace(tmp, "\n", "", -1) |
103 | 100 | ip := net.ParseIP(ipv6) |
104 | 101 | if ip != nil { |
105 | | - log.Println("got ipv6 addr:", ip.String()) |
106 | | - return ip.String(), nil |
| 102 | + _ = resp.Body.Close() |
| 103 | + return ip.String() |
107 | 104 | } |
108 | 105 | } |
109 | | - return "", errors.New("pv6 not found") |
| 106 | + return "" |
110 | 107 | } |
0 commit comments