From ae1c3b5bc87d2b010b82d22a2c4e8fd4a513bc96 Mon Sep 17 00:00:00 2001 From: qydysky Date: Sat, 24 Aug 2024 01:48:24 +0800 Subject: [PATCH] 1 --- sys/Sys.go | 37 +++++++++++++++++++++++++++++++++++++ sys/Sys_test.go | 1 + 2 files changed, 38 insertions(+) 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()) } -- 2.39.2