nezha/cmd/agent/monitor/myip.go

75 lines
1.6 KiB
Go
Raw Normal View History

2021-03-22 09:40:50 -04:00
package monitor
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/naiba/nezha/pkg/utils"
2021-03-22 09:40:50 -04:00
)
type geoIP struct {
CountryCode string `json:"country_code,omitempty"`
IP string `json:"ip,omitempty"`
2021-07-08 12:01:58 -04:00
Query string `json:"query,omitempty"`
2021-03-22 09:40:50 -04:00
}
var (
2021-07-08 12:01:58 -04:00
geoIPApiList = []string{
2021-07-05 01:44:21 -04:00
"https://api.ip.sb/geoip",
"https://ip.seeip.org/geoip",
"https://ipapi.co/json",
2021-07-08 12:01:58 -04:00
"https://freegeoip.app/json/",
"http://ip-api.com/json/",
"https://extreme-ip-lookup.com/json/",
}
cachedIP, cachedCountry string
httpClientV4 = utils.NewSingleStackHTTPClient(time.Second*20, time.Second*5, time.Second*10, false)
httpClientV6 = utils.NewSingleStackHTTPClient(time.Second*20, time.Second*5, time.Second*10, true)
)
2021-03-22 09:40:50 -04:00
func UpdateIP() {
for {
2021-07-08 12:01:58 -04:00
ipv4 := fetchGeoIP(geoIPApiList, false)
ipv6 := fetchGeoIP(geoIPApiList, true)
2021-05-27 08:48:12 -04:00
cachedIP = fmt.Sprintf("ip(v4:%s,v6:[%s])", ipv4.IP, ipv6.IP)
2021-03-22 09:40:50 -04:00
if ipv4.CountryCode != "" {
cachedCountry = ipv4.CountryCode
} else if ipv6.CountryCode != "" {
cachedCountry = ipv6.CountryCode
}
time.Sleep(time.Minute * 10)
}
}
func fetchGeoIP(servers []string, isV6 bool) geoIP {
2021-03-22 09:40:50 -04:00
var ip geoIP
var resp *http.Response
var err error
2021-03-22 09:40:50 -04:00
for i := 0; i < len(servers); i++ {
if isV6 {
resp, err = httpClientV6.Get(servers[i])
} else {
resp, err = httpClientV4.Get(servers[i])
}
2021-03-22 09:40:50 -04:00
if err == nil {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
continue
}
resp.Body.Close()
err = json.Unmarshal(body, &ip)
if err != nil {
continue
}
2021-07-08 12:01:58 -04:00
if ip.IP == "" && ip.Query != "" {
ip.IP = ip.Query
}
2021-03-22 09:40:50 -04:00
return ip
}
}
return ip
}