1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package main
import (
"fmt"
"log"
"net"
)
func main() {
//源端口,目的端口
var fromport, toport int = 2222, 88
fromaddr := fmt.Sprintf( "127.0.0.1:%d" , fromport)
toaddr := fmt.Sprintf( "127.0.0.1:%d" , toport)
fromlistener, err := net.Listen( "tcp" , fromaddr)
if err != nil {
log.Fatal( "Unable to listen on: %s, error: %s\n" , fromaddr, err.Error())
}
defer fromlistener.Close()
for {
fromcon, err := fromlistener.Accept()
if err != nil {
fmt.Printf( "Unable to accept a request, error: %s\n" , err.Error())
} else {
fmt.Println( "new connect:" + fromcon.RemoteAddr().String())
}
//这边最好也做个协程,防止阻塞
toCon, err := net.Dial( "tcp" , toaddr)
if err != nil {
fmt.Printf( "can not connect to %s\n" , toaddr)
continue
}
go handleConnection(fromcon, toCon)
go handleConnection(toCon, fromcon)
}
}
func handleConnection(r, w net.Conn) {
defer r.Close()
defer w.Close()
var buffer = make([]byte, 100000)
for {
n, err := r.Read(buffer)
if err != nil {
break
}
n, err = w.Write(buffer[:n])
if err != nil {
break
}
}
}
|
参考链接:GO语言实现TCP端口转发【代码】_苏南生的CSDN博客-CSDN博客
标签:err,nil,fmt,端口,TCP,GO,net,fromcon From: https://www.cnblogs.com/lvjinlin/p/18123694