1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| package main
import ( "bufio" "fmt" "math/big" "net" "os" "regexp" )
func main() { file, err := os.Open("ips.txt") if err != nil { fmt.Println("打开文件失败:", err) return } defer file.Close() ipPattern := `(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2})` re := regexp.MustCompile(ipPattern) scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() ips := re.FindAllString(line, -1) for _, ip := range ips { fmt.Println("找到ip地址:", ip) play(ip) } } }
func play(bigIPNet string) { _, ipnet, err := net.ParseCIDR(bigIPNet) if err != nil { fmt.Println("解析 IP 地址网时出错:", err) return } subnetMask := ipnet.Mask ipCount := calculateIPCount(subnetMask) subnets := splitIPNet(ipnet, 24, ipCount/256) fmt.Println(subnets) str := "" for v := range subnets { str += subnets[v].String() + "\n" } file, err := os.OpenFile("reachable_ips.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777) if err != nil { fmt.Println("打开文档出错:", err) return } defer file.Close() _, err = fmt.Fprintln(file, str) if err != nil { fmt.Println("写入数据出错:", err) } }
func calculateIPCount(subnetMask net.IPMask) int { mask := net.IPMask(subnetMask) ipCount := 1 for _, b := range mask { ipCount *= 256 - int(b) } return ipCount }
func splitIPNet(ipnet *net.IPNet, newPrefixLen, numSubnets int) []*net.IPNet { ip := ipnet.IP subnetMask := net.CIDRMask(newPrefixLen, 32) subnetSize := new(big.Int).SetBit(new(big.Int), 32-newPrefixLen, 1)
subnets := make([]*net.IPNet, numSubnets) for i := 0; i < numSubnets; i++ { newSubnet := &net.IPNet{ IP: ip, Mask: subnetMask, } subnets[i] = newSubnet
ip = nextIP(ip, subnetSize) } return subnets }
func nextIP(ip net.IP, increment *big.Int) net.IP { ipInt := new(big.Int) ipInt.SetBytes(ip.To4()) ipInt.Add(ipInt, increment) nextIP := make(net.IP, 4) copy(nextIP, ipInt.Bytes()) return nextIP }
|