From: qydysky Date: Fri, 23 Aug 2024 17:48:24 +0000 (+0800) Subject: 1 X-Git-Tag: v0.28.20240823175400 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=ae1c3b5bc87d2b010b82d22a2c4e8fd4a513bc96;p=part%2F.git 1 --- diff --git a/sys/Sys.go b/sys/Sys.go index 776282c..4cc4093 100644 --- a/sys/Sys.go +++ b/sys/Sys.go @@ -137,6 +137,7 @@ func (t *sys) GetTmpFile(pdir string) string { return name } +// Deprecated: use GetIpByCidr func GetIntranetIp(cidr string) (ips []string) { netInterfaces, err := net.Interfaces() if err != nil { @@ -180,6 +181,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]) + if err != nil { + return nil, err + } + + 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) { + ips = append(ips, ipnet.IP.String()) + } + } + } + } + } + } + + return +} + func (t *sys) CheckProgram(pros ...string) []int { return Ppart.PCheck(pros) } diff --git a/sys/Sys_test.go b/sys/Sys_test.go index 7134203..5c69707 100644 --- a/sys/Sys_test.go +++ b/sys/Sys_test.go @@ -6,4 +6,5 @@ import ( func Test_customMap(t *testing.T) { t.Log(GetIntranetIp(`192.168.0.0/16`)) + t.Log(GetIpByCidr()) }