diff --git a/internal/monitor/monitor.go b/internal/monitor/monitor.go index 32d6590..a09e50d 100644 --- a/internal/monitor/monitor.go +++ b/internal/monitor/monitor.go @@ -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, } diff --git a/internal/monitor/myip.go b/internal/monitor/myip.go index edc469d..d7e6cc4 100644 --- a/internal/monitor/myip.go +++ b/internal/monitor/myip.go @@ -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, ";") +} diff --git a/model/node.go b/model/node.go index 2ebe4e3..44cca5c 100644 --- a/model/node.go +++ b/model/node.go @@ -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"` }