]> 127.0.0.1 Git - part/.git/commitdiff
1 v0.28.20240823175400
authorqydysky <qydysky@foxmail.com>
Fri, 23 Aug 2024 17:48:24 +0000 (01:48 +0800)
committerqydysky <qydysky@foxmail.com>
Fri, 23 Aug 2024 17:48:24 +0000 (01:48 +0800)
sys/Sys.go
sys/Sys_test.go

index 776282c9b537c782d891a487755bd68e7524a6da..4cc40936f43ac0de0f0f03d6892537f1a94cb634 100644 (file)
@@ -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)
 }
index 7134203856e422934f7585d2272e252161903aeb..5c697072592b25b4946647fbe89178ef995844bc 100644 (file)
@@ -6,4 +6,5 @@ import (
 
 func Test_customMap(t *testing.T) {
        t.Log(GetIntranetIp(`192.168.0.0/16`))
+       t.Log(GetIpByCidr())
 }