简易版
package main
func worker(ports,results chan int){
for p:=range ports{
address:=fmt.Sprintf("bilibili.com:%d",p)
conn,err:=net.Dial("tcp",address)
if err!=nil{
result<-0
continue
}
conn.Close()
results<-p
}
}
func main(){
ports:=make(chan int,100)
results:=make(chan int)
var openports []int
for i:=0;i<=cap(ports);i++{
go worker(ports,results)
}
go func(){
for i:=1;i<=1024;i++{
ports<-i
}
}()
for i:=0;i<1024;i++{
ports:=<-results
if port!=0{
openports=append(openports,port)
}
}
close(ports)
close(results)
sort.Ints(openports)
for _,port:=range openports{
fmt.Prinf("%d open\n",port)
}
}
能够解析IP 端口字符串的TCP全连接扫描器
/scanner/tcp-scanner.go
package scanner
func Connect(ip string,port int)(net.Conn,err){
address:=fmt.Sprintf("%v:%v",ip,port)
conn,err:=net.DialTimeout("tcp",address,1*time.Second)
defer func(){
if conn!=nil{
conn.Close()
}
}()
return conn,err
}
util/util.go
package util
func GetPorts(selection string)([]int,error){
ports:=make([]int,0)
if selections==""{
return ports,nil
}
ranges:=strings.Split(selection,",")
for _,r:=range ranges{
r=strings.TrimSpace(r)
if strings.Contains(r,"-"){
parts:=strings.Split(r,"-")
if len(parts)!=2{
return nil,fmt.Errorf("Invalid Port Selection segment :'%s'",r)
}
start,err:=strconv.Atio(parts[0])
if err!=nil{
return nil,fmt.Errorf("Invalid port number:'%s'",parts[0])
}
end,err:=strconv.Atio(parts[1])
if err!=nil{
return nil,fmt.Errorf("Invalid port number:'%s'",ports[1])
}
if start>end{
return nil,fmt.Errorf("Invalid port range:%d-%d",start,end)
}
for i:=start;i<=end;i++{
ports=append(ports,i)
}
}else{
if port,err:=strconv.Atio(r);err!=nil{
return nil,fmt.Errorf("Invalid port number:'%s'",r)
}else{
ports=append(ports,port)
}
}
}
return ports,nil
}
func GetIpList(ips string)([]net.IP,error){
addressList,err:=iprange.ParseList(ips)
if err!=nil{
return nil,err
}
list:=addrssList.Expand()
return list,err
}
main.go
package main
func main(){
if len(os.Args)==3{
ipList:=os.Args[1]
portsList:=os.Args[2]
ips,_:=util.GetIpList(iplist)
ports,_:=util.GetPortList(portsList)
for _,ip :=range ips{
for_,port:=range ports{
_,err:=scanner.Connect(ip.String(),port)
if err!=nil{
continue
}
fmt.Printf("ip:%v,port:%v is open\n",ip,port)
}
}
}else{
fmt.Printf("%v iplist port \n",os.Arg[0])
}
}
标签:err,nil,端口扫描,ip,fmt,TCP,ports,Golang,port
From: https://www.cnblogs.com/Weber-security/p/17347934.html