Ai
1 Star 0 Fork 0

zhxlp/golang-study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
public_ip.go 2.06 KB
一键复制 编辑 原始数据 按行查看 历史
zhxlp 提交于 2022-08-20 23:43 +08:00 . 获取公网IP
package api
import (
"fmt"
"io"
"net/http"
"time"
log "github.com/sirupsen/logrus"
)
// func init() {
// log.SetLevel(log.DebugLevel)
// }
var IPV4_API = []string{"http://ipv4.ddnspod.com", "http://ipv4.testipv6.cn/ip/", "http://ipv4.icanhazip.com/", "https://api4.ipify.org/", "https://ip4.seeip.org/", "http://api-ipv4.ip.sb/ip", "http://v4.ipv6-test.com/api/myip.php"}
var IPV6_API = []string{"http://ipv6.ddnspod.com", "http://ipv6.testipv6.cn/ip/", "http://ipv6.icanhazip.com/", "https://api6.ipify.org/", "https://ip6.seeip.org/", "http://api-ipv6.ip.sb/ip", "http://v6.ipv6-test.com/api/myip.php"}
func request(url string) (string, error) {
client := &http.Client{Transport: HttpTransport, Timeout: 3 * time.Second}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if !(res.StatusCode >= 200 && res.StatusCode < 300) {
return "", fmt.Errorf("error status code: %d", res.StatusCode)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// 获取当前上网的公网ip地址
// @param ipType: V4 或 V6
func GetPublicIP(ipType string) (string, error) {
var apis []string
var matchFn func(s string) (string, error)
if ipType == "V6" {
apis = IPV6_API
matchFn = MatchIPv6
} else if ipType == "V4" {
apis = IPV4_API
matchFn = MatchIPv4
} else {
return "", fmt.Errorf("error ipType: %s", ipType)
}
res := make(chan string, len(apis))
for _, v := range apis {
go func(url string) {
body, err := request(url)
if err != nil {
log.Error(err)
res <- ""
return
}
ip, err := matchFn(body)
if err != nil {
log.Error(err)
res <- ""
return
}
res <- ip
}(v)
}
ips := map[string]int{}
successCount := 0
for range apis {
v := <-res
if v == "" {
continue
}
c := ips[v]
ips[v] = c + 1
successCount += 1
}
for k, v := range ips {
if v >= successCount/2 {
return k, nil
}
}
return "", fmt.Errorf("not found ip%s address", ipType)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zhxlp/golang-study.git
git@gitee.com:zhxlp/golang-study.git
zhxlp
golang-study
golang-study
cbd539ebca60

搜索帮助