整体代码如下,提供golang新手学习
不懂的可以看往期视频,golang开发端口扫描器
package main
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
)
func PortScan(ip string,port int,result chan int,portpool *int){
portok:=strconv.Itoa(port)
_,err:=net.Dial("tcp",ip+":"+portok)
if(err==nil){
fmt.Println(ip+":"+portok+" 端口被打开")
result<-1
}else{
result<-0
}
*portpool+=1
}
func main(){
resule:=make(chan int,111111)
var portpool int
var ipaddr string
var port string
var port1 int
var port2 int
for k,v :=range os.Args{
if v=="-h"{
ipaddr=os.Args[k+1]
}
if v=="-p"{
port=os.Args[k+1]
}
}
if ipaddr==""{
fmt.Println("请添加要扫描的主机")
os.Exit(0)
}
if port==""{
fmt.Println("请添加要扫描的端口")
os.Exit(0)
}
if strings.Contains(port,"-")==true{
portok:=strings.Split(port,"-")
port1x,_:=strconv.Atoi(portok[0])
port2x,_:=strconv.Atoi(portok[1])
port1=port1x
port2=port2x
}else{
portok,_:=strconv.Atoi(port)
go PortScan(ipaddr,portok,resule,&portpool)
}
for i:=0;i<port2;i++{
go PortScan("127.0.0.1",port1+i,resule,&portpool)
}
for{
select {
case <-time.After(time.Second*3):
if(portpool==port2){
goto s
}else{
<-resule
}
}
}
s:
os.Exit(0)
}