import (
"errors"
"fmt"
+ "iter"
"net"
"os"
"path/filepath"
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 {