遍历中国所有IP地址

#main

package main

import (
	"libmy"
	"fmt"
)

var iplistchan chan string
var iplistsuccess chan string
var hostsuccess chan string

func insertintochan(iplist []string,iplistchan chan string)  {
	for _,ipcidr := range iplist {
		hosts, _ := libmy.Hosts(ipcidr)
		for _, ip := range hosts {
			iplistchan <- ip
		}
	}
	close(iplistchan)
	iplistsuccess <- "good"

}

func worker(iplistchan chan string)  {
	for {
		if elem, ok := <-iplistchan; ok {
			fmt.Println(elem)
		} else {
			break
		}
	}
	hostsuccess <- "good"
}


func main()  {
	iplistchan=make(chan string ,1000)
	iplistsuccess=make(chan string)
	hostsuccess=make(chan string)
	iplist:=libmy.ReadList("cn1.zone")
	go insertintochan(iplist,iplistchan)

	for i:=0;i<13;i++ {
		go worker(iplistchan)
	}
	<-iplistsuccess
	for j:=0;j<13;j++ {
		<-hostsuccess
	}
}

#lib.go

package libmy

import "net"
import "os"
import "bufio"
import "fmt"
import "strings"

func Hosts(cidr string) ([]string, error) {
	ip, ipnet, err := net.ParseCIDR(cidr)
	if err != nil {
		return nil, err
	}

	var ips []string
	for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
		ips = append(ips, ip.String())
	}
	return ips[1 : len(ips)-1], nil
}

func inc(ip net.IP) {
	for j := len(ip) - 1; j >= 0; j-- {
		ip[j]++
		if ip[j] > 0 {
			break
		}
	}
}

func ReadList(fileName string) ( [] string) {
	ipListFile, err := os.Open(fileName)
	if err != nil {
		fmt.Println("ERR::" + err.Error())
		os.Exit(1)
	}
	defer ipListFile.Close()
	ipList:=make([]string,0)
	scanner := bufio.NewScanner(ipListFile)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		ipinfo := strings.TrimSpace(scanner.Text())
		ipList = append(ipList, ipinfo)
	}
	return ipList
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注