初学go,写一个端口转发工具。很方便的小工具,希望能对大家学习go语言有所帮助。
```
packagemain
import(
"fmt"
"io"
"net"
"sync"
)
varlocksync.Mutex
vartrueList[]string
varipstring
varliststring
funcmain(){
ip="0.0.0.0:888"
server()
}
funcserver(){
fmt.Printf("Listening%s",ip)
lis,err:=net.Listen("tcp",ip)
iferr!=nil{
fmt.Println(err)
return
}
deferlis.Close()
for{
conn,err:=lis.Accept()
iferr!=nil{
fmt.Println("建立连接错误:%v\n",err)
continue
}
fmt.Println(conn.RemoteAddr(),conn.LocalAddr())
gohandle(conn)
}
}
funchandle(sconnnet.Conn){
defersconn.Close()
ip:="127.0.0.1:8888"
dconn,err:=net.Dial("tcp",ip)
iferr!=nil{
fmt.Printf("连接%v失败:%v\n",ip,err)
return
}
ExitChan:=make(chanbool,1)
gofunc(sconnnet.Conn,dconnnet.Conn,Exitchanbool){
io.Copy(dconn,sconn)
ExitChan<-true
}(sconn,dconn,ExitChan)
gofunc(sconnnet.Conn,dconnnet.Conn,Exitchanbool){
io.Copy(sconn,dconn)
ExitChan<-true
}(sconn,dconn,ExitChan)
<-ExitChan
dconn.Close()
}
```
有疑问加站长微信联系(非本文作者)