ipnet.go
1 // Copyright (c) 2024-2026 Tencent Zhuque Lab. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Requirement: Any integration or derivative work must explicitly attribute 16 // Tencent Zhuque Lab (https://github.com/Tencent/AI-Infra-Guard) in its 17 // documentation or user interface, as detailed in the NOTICE file. 18 19 // Package runner ipnet实现 20 package runner 21 22 import ( 23 "encoding/binary" 24 "github.com/Tencent/AI-Infra-Guard/common/utils" 25 "net" 26 "strings" 27 ) 28 29 // Targets returns all the targets within a cidr range or the single target 30 func Targets(target string) chan string { 31 results := make(chan string) 32 go func() { 33 defer close(results) 34 35 // A valid target does not contain: 36 // * 37 // spaces 38 if strings.ContainsAny(target, " *") { 39 return 40 } 41 42 // test if the target is a cidr 43 if utils.IsCIDR(target) { 44 cidrIps, err := IPAddresses(target) 45 if err != nil { 46 return 47 } 48 for _, ip := range cidrIps { 49 results <- ip 50 } 51 } else { 52 results <- target 53 } 54 }() 55 return results 56 } 57 58 // IPAddresses returns all the IP addresses in a CIDR 59 func IPAddresses(cidr string) ([]string, error) { 60 _, ipnet, err := net.ParseCIDR(cidr) 61 if err != nil { 62 return []string{}, err 63 } 64 return IPAddressesIPnet(ipnet), nil 65 } 66 67 // IPAddressesIPnet returns all IP addresses in an IPNet. 68 func IPAddressesIPnet(ipnet *net.IPNet) (ips []string) { 69 // convert IPNet struct mask and address to uint32 70 mask := binary.BigEndian.Uint32(ipnet.Mask) 71 start := binary.BigEndian.Uint32(ipnet.IP) 72 73 // find the final address 74 finish := (start & mask) | (mask ^ 0xffffffff) 75 76 // loop through addresses as uint32 77 for i := start; i <= finish; i++ { 78 // convert back to net.IP 79 ip := make(net.IP, 4) 80 binary.BigEndian.PutUint32(ip, i) 81 ips = append(ips, ip.String()) 82 } 83 return ips 84 }