TCP扫描器
在worker函数中通过net.Dial测试端口连通,并把worker放到go routine中运行,port作为管道在主程序和携程中传递扫描信息
package main
import (
"fmt"
"net"
"sort"
)
func worker(ports chan int, results chan int) {
for p := range ports {
address := fmt.Sprintf("127.0.0.1: %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 <= 1024; i++ {
ports <- i
}
}()
for i := 0; i < 1024; 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)
}
}
TCP代理
建立监听接收来自客户端的消息,通过net.Dial连接目标服务器,并将客户端的消息通过io.Copy复制到目标服务器
package main
import (
"fmt"
"io"
"log"
"net"
)
func handle(src net.Conn) {
dst, err := net.Dial("tcp", "192.168.1.52: 8089")
if err != nil {
log.Fatal("Unable to connect")
}
defer dst.Close()
go func() {
if _, err := io.Copy(dst, src); err != nil {
log.Fatal(err)
}
}()
if _, err := io.Copy(src, dst); err != nil {
log.Fatal(err)
}
}
func main() {
fmt.Println("Waiting for connect")
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal("Unable to accept connection")
}
fmt.Println("Accept connection")
go handle(conn)
}
}
标签:扫描器,log,err,nil,fmt,TCP,Go,net,Fatal
From: https://www.cnblogs.com/z5onk0/p/18247436