法一
package main
import (
"fmt"
"net"
)
func main() {
var datas []int // 用来保存扫描到的port
var ports chan int = make(chan int)
var done chan int = make(chan int)
// 创建消费者
for i := 0; i < 10; i++ {
go func() {
for {
port, ok := <-ports
if !ok {
break
}
add := fmt.Sprintf("scanme.namp.com:%d", port)
_, err := net.Dial("tcp", add)
if err != nil {
//log.Fatalln(err)
fmt.Println(err)
} else {
datas = append(datas, port)
}
}
done <- 1
}()
}
for i := 1; i < 100; i++ {
ports <- i
}
for v := range done {
fmt.Println(v)
}
fmt.Println(datas)
}
法二
package main
import (
"fmt"
"net"
"sort"
)
func worker(ports, results chan int) {
for p := range ports {
address := fmt.Sprintf("192.168.1.19:%d", p)
conn, err := net.Dial("tcp", address)
if err != nil {
results <- 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 <= 65535; i++ {
ports <- i
}
}()
for i := 0; i < 65535; i++ {
port := <-results
if port != 0 {
openports = append(openports, port)
}
}
close(ports)
close(results)
sort.Ints(openports)
for _, port := range openports {
fmt.Printf("%d open\n", port)
}
}
网友评论