Go语言实现的简单网络端口扫描方法
本文实例讲述了Go语言实现的简单网络端口扫描方法。分享给大家供大家参考。具体实现方法如下:
packagemain import( "net" "fmt" "os" "runtime" "time" "strconv" )
funcloop(startport,endportint,inportchanint){ fori:=startport;i<=endport;i++{ inport<-i } }
funcscanner(inport,outport,outchanint,ipnet.IP,endportint){ for{ in:=<-inport //fmt.Println(in) tcpaddr:=&net.TCPAddr{ip,in} conn,err:=net.DialTCP("tcp",nil,tcpaddr) iferr!=nil{ outport<-0 }else{ outport<-in } conn.Close() ifin==endport{ out<-in } } }
funcmain(){ starttime:=time.Now().Unix() runtime.GOMAXPROCS(4) inport:=make(chanint) outport:=make(chanint) out:=make(chanint) collect:=[]int{} iflen(os.Args)!=4{ fmt.Println("Usage:scanner.exeIPstartportendport") fmt.Println("Endportmustbelargerthanstartport") os.Exit(0) } ip:=net.ParseIP(os.Args[1]) if(os.Args[3]<os.Args[2]){ fmt.Println("Usage:scannerIPstartportendport") fmt.Println("Endportmustbelargerthanstartport") os.Exit(0) } startport,_:=strconv.Atoi(os.Args[2]) endport,_:=strconv.Atoi(os.Args[3]) goloop(startport,endport,inport) for{ select{ case<-out: fmt.Println(collect) endtime:=time.Now().Unix() fmt.Println("Thescanprocesshasspent",endtime-starttime,"second") os.Exit(0) default: goscanner(inport,outport,out,ip,endport) port:=<-outport ifport!=0{ collect=append(collect,port) } } } }