Golang tcp 转发
第一版本
accept获取的Conn里的localAddr做为源地址,remoteAddr来做为目的地址
// tcpForward
package main
import (
"fmt"
"net"
"os"
)
func TcpForward(port int) {
lisPort := fmt.Sprint(":", port)
listen, err := net.Listen("tcp", lisPort)
if err != nil {
fmt.Println("fault to listen,err: %s", err.Error())
os.Exit(1)
}
defer listen.Close()
fmt.Println("listenning now!")
for {
fromConn, err := listen.Accept()
if err != nil {
fmt.Println("fault,err: %s", err.Error())
fromConn.Close()
continue
}
go toDial(fromConn)
}
}
func toDial(fromConn net.Conn) {
toAddr := fromConn.RemoteAddr()
toConn, err := net.Dial("tcp", toAddr.String())
if err != nil {
fmt.Println("fault,err: %s", err.Error())
toConn.Close()
}
fmt.Println("%s to %s", fromConn.LocalAddr().String(), toConn.RemoteAddr().String())
go copy(fromConn, toConn, 512)
go copy(toConn, fromConn, 512)
}
func copy(f, t net.Conn, n int) {
defer f.Close()
defer t.Close()
var buf = make([]byte, n)
for {
count, err := f.Read(buf)
if err != nil {
fmt.Println("fault,err: %s", err.Error())
break
}
count, err = t.Write(buf[:count])
if err != nil {
fmt.Println("fault,err: %s", err.Error())
break
}
}
}
win设置代理,用edge访问网页报错!!!
报错信息:
C:/Go/bin/go.exe build [C:/Users/imcjb/Desktop/egoweb]
成功: 进程退出代码 0.
C:/Users/imcjb/Desktop/egoweb/egoweb.exe [C:/Users/imcjb/Desktop/egoweb]
Hello World!
C:UsersimcjbDesktopegowebegoweb.exe
listenning now!
fault,err: %s dial tcp 127.0.0.1:53391: connectex: No connection could be made because the target machine actively refused it.
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x18 pc=0x6154cf]
goroutine 20 [running]:
main.toDial(0x6f4a20, 0xc000092038)
C:/Users/imcjb/Desktop/egoweb/tcpForward.go:36 +0x3bf
created by main.TcpForward
C:/Users/imcjb/Desktop/egoweb/tcpForward.go:26 +0x2db
fault,err: %s dial tcp 127.0.0.1:53392: connectex: No connection could be made because the target machine actively refused it.
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x18 pc=0x6154cf]
goroutine 19 [running]:
main.toDial(0x6f4a20, 0xc000092030)
C:/Users/imcjb/Desktop/egoweb/tcpForward.go:36 +0x3bf
created by main.TcpForward
C:/Users/imcjb/Desktop/egoweb/tcpForward.go:26 +0x2db
错误: 进程退出代码 2.
错误猜测
这里的remoteaddr返回的其实是转发前的真实ip,而非目的ip
代码部分还有一个小问题println、sprintf使用错误,他们的参数是interface{}