修改bug

This commit is contained in:
wangjian 2023-06-17 09:40:49 +08:00
parent 2a22781b46
commit 23219a5874
3 changed files with 35 additions and 7 deletions

View File

@ -67,7 +67,7 @@ func GetHost(cfg *config.AgentConfig) *model.Node {
if cachedBootTime.IsZero() {
cachedBootTime = time.Unix(int64(hi.BootTime), 0)
}
UpdateIP()
return &model.Node{
NodeGuid: hi.HostID,
NodeName: cfg.Point,
@ -82,6 +82,7 @@ func GetHost(cfg *config.AgentConfig) *model.Node {
Virtualization: hi.VirtualizationSystem,
BootTime: hi.BootTime,
IP: cachedIP,
LocalIP: GetLocalIp(),
CountryCode: strings.ToLower(cachedCountry),
Version: Version,
}

View File

@ -4,7 +4,8 @@ import (
"encoding/json"
"environmentCaptureAgent/pkg/utils"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"strings"
"time"
@ -18,7 +19,6 @@ type geoIP struct {
var (
geoIPApiList = []string{
"https://api.ip.sb/geoip",
"https://ip.seeip.org/geoip",
"https://ipapi.co/json",
"https://freegeoip.app/json/",
@ -31,11 +31,12 @@ var (
)
func UpdateIP() {
var count = 0
for {
ipv4 := fetchGeoIP(geoIPApiList, false)
ipv6 := fetchGeoIP(geoIPApiList, true)
if ipv4.IP == "" && ipv6.IP == "" {
time.Sleep(time.Minute)
time.Sleep(time.Second)
continue
}
if ipv4.IP == "" || ipv6.IP == "" {
@ -48,7 +49,14 @@ func UpdateIP() {
} else if ipv6.CountryCode != "" {
cachedCountry = ipv6.CountryCode
}
time.Sleep(time.Minute * 30)
if len(cachedIP) > 0 || len(cachedCountry) > 0 {
break
}
count += 1
if count > 3 {
break
}
time.Sleep(time.Second * 30)
}
}
@ -63,11 +71,11 @@ func fetchGeoIP(servers []string, isV6 bool) geoIP {
resp, err = httpClientV4.Get(servers[i])
}
if err == nil {
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
continue
}
resp.Body.Close()
_ = resp.Body.Close()
err = json.Unmarshal(body, &ip)
if err != nil {
continue
@ -88,3 +96,21 @@ func fetchGeoIP(servers []string, isV6 bool) geoIP {
}
return ip
}
func GetLocalIp() string {
ipAddr := make([]string, 0)
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
return ""
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ipAddr = append(ipAddr, ipNet.IP.String())
}
}
}
return strings.Join(ipAddr, ";")
}

View File

@ -17,6 +17,7 @@ type Node struct {
Virtualization string `json:"virtualization,omitempty"`
BootTime uint64 `json:"bootTime,omitempty"`
IP string `json:"ip"`
LocalIP string `json:"localIP"`
CountryCode string `json:"countryCode,omitempty"`
Version string `json:"version,omitempty"`
}