From: qydysky Date: Fri, 23 Aug 2024 18:26:48 +0000 (+0800) Subject: 1 X-Git-Tag: v0.28.20240823183215 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=719a4bdfad2f109ca3d48c979bfede781d362f4e;p=part%2F.git 1 --- diff --git a/sys/Sys.go b/sys/Sys.go index 4cc4093..ff007ac 100644 --- a/sys/Sys.go +++ b/sys/Sys.go @@ -3,6 +3,7 @@ package part import ( "errors" "fmt" + "iter" "net" "os" "path/filepath" @@ -181,40 +182,42 @@ func GetIntranetIp(cidr string) (ips []string) { return []string{"127.0.0.1"} } -func GetIpByCidr(cidr ...string) (ips []string, e error) { - netInterfaces, err := net.Interfaces() - if err != nil { - return nil, err - } - - var cidrN *net.IPNet - if len(cidr) == 0 { - cidr = append(cidr, `0.0.0.0/0`) - cidr = append(cidr, `::/0`) - } - - for i := 0; i < len(cidr); i++ { - _, cidrN, err = net.ParseCIDR(cidr[i]) +func GetIpByCidr(cidr ...string) (seq iter.Seq[net.IP]) { + return func(yield func(net.IP) bool) { + netInterfaces, err := net.Interfaces() if err != nil { - return nil, err + return } - for i := 0; i < len(netInterfaces); i++ { - if (netInterfaces[i].Flags & net.FlagUp) != 0 { - addrs, _ := netInterfaces[i].Addrs() + var cidrN *net.IPNet + if len(cidr) == 0 { + cidr = append(cidr, `0.0.0.0/0`) + cidr = append(cidr, `::/0`) + } - for _, address := range addrs { - if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if cidrN != nil && cidrN.Contains(ipnet.IP) { - ips = append(ips, ipnet.IP.String()) + for i := 0; i < len(cidr); i++ { + _, cidrN, err = net.ParseCIDR(cidr[i]) + if err != nil { + return + } + + for i := 0; i < len(netInterfaces); i++ { + if (netInterfaces[i].Flags & net.FlagUp) != 0 { + addrs, _ := netInterfaces[i].Addrs() + + for _, address := range addrs { + if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if cidrN != nil && cidrN.Contains(ipnet.IP) { + if !yield(ipnet.IP) { + return + } + } } } } } } } - - return } func (t *sys) CheckProgram(pros ...string) []int { diff --git a/sys/Sys_test.go b/sys/Sys_test.go index 5c69707..d6e0645 100644 --- a/sys/Sys_test.go +++ b/sys/Sys_test.go @@ -6,5 +6,7 @@ import ( func Test_customMap(t *testing.T) { t.Log(GetIntranetIp(`192.168.0.0/16`)) - t.Log(GetIpByCidr()) + for ip := range GetIpByCidr() { + t.Log(ip.String()) + } }